liveBook · Manning

Vector

As explained in Embedded Software with Rust

A vector is Rust's owned, growable vector type for storing elements contiguously on dynamically allocated storage.

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

How Embedded Software with Rust covers it

How deep it goes
Explains growth, reallocation, preallocation, and fallible reservation through allocation behavior and code examples.
Examples
Uses a growing event log and compares pushing 100 samples with reserving capacity for them first.
What it assumes
Assumes Rust familiarity and requires alloc plus a global allocator for vectors in no_std; contrasts them with fixed-size arrays.
What you can do after
Apply it via Vec::with_capacity and try_reserve to manage growth and handle allocation failure.
How it connects
Connects Vec to alloc, global allocators, String, fixed-size arrays, and heapless::String.

Also explained in

Compare how 14 books explain vector →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.