A Rust `Vec<T>` owns a contiguous, growable collection whose elements live in dynamically allocated storage. In embedded firmware, a vector can hold data that grows at runtime, but using one requires heap support. section 7.2.4 section 1.3.1
Plan for how a vector allocates and what happens when memory is scarce:
- Starting with `Vec::new`, pushes that exceed capacity can trigger a larger allocation, copy existing elements, and free the old backing storage. section 7.2.6
- `Vec::with_capacity` reserves space up front, reducing reallocations during later pushes and making their timing more predictable. section 7.2.6
- In `no_std`, vectors require the `alloc` crate and a global allocator. Allocation failure normally invokes the panic handler; `try_reserve` provides a fallible alternative. section 7.2.4 section 1.3.1
let mut v: Vec<u32> = Vec::new();
// Try to ensure capacity for 1024 elements.
// Returns Err(TryReserveError) if the allocator cannot satisfy the request.
match v.try_reserve(1024) {
Ok(()) => {
for i in 0..1024 { v.push(i); }
}
Err(_) => {
// Recover gracefully: log, fall back to a smaller buffer, retry later.
}
}
This example reserves capacity fallibly before pushing elements, allowing the program to choose a recovery path if allocation fails. section 7.2.4
Use heap-backed vectors only where their flexibility is worth the RAM and allocation costs. For fixed-size storage in pure `no_std`, a statically allocated array is an alternative; heap-allocated buffers may also land in RAM that a particular DMA controller cannot reach. section 1.3.1 section 7.2.6













