liveBook · Manning

Arrayvec

As explained in Embedded Software with Rust

arrayvec is a Rust library providing vector-like collections backed by fixed-capacity inline arrays and supporting no_std environments.

arrayvec provides fixed-capacity, vector-like collections backed by inline arrays. ArrayVec<T, N> stores elements without heap allocation, while ArrayString<N> stores bounded strings. This makes the crate useful for no_std firmware that needs predictable memory use and avoids allocator overhead or fragmentation. section 7.0 section 7.3.2

Choose arrayvec when the required collection types and their maximum capacities are known:

  • Use ArrayVec<T, N> for a bounded sequence whose storage should remain inline. section 7.3.2
  • Use ArrayString<N> for a bounded string without installing a global allocator. section 7.3.2
  • Use push and push_str when overflow means a programmer error; both panic if capacity is exceeded. section 7.3.2
  • Use try_push and try_push_str when capacity exhaustion can result from runtime input and must be handled explicitly. section 7.3.2
  • Prefer heapless when the project also needs queues or other collection types; prefer arrayvec when only a vector or string is needed. section 7.3.2 section 7.3.4
use arrayvec::{ArrayString, ArrayVec};

let mut buffer: ArrayVec<u8, 16> = ArrayVec::new();
buffer.push(0x33);          // OK
// ...fifteen more pushes...
buffer.push(0x55);          // PANIC if already full

let mut name: ArrayString<32> = ArrayString::new();
name.push_str("sensor-01"); // OK
name.push_str("...");       // PANIC if the result exceeds 32 bytes

Shows inline storage for bytes and strings, including the panic behavior of operations that exceed capacity. section 7.3.2

Make overflow fallible

A caller that has verified room can use buffer.try_push(0x55).expect("caller verified capacity"); a caller that can tolerate rejected input can use name.try_push_str("extra").ok(). section 7.3.2

How Embedded Software with Rust covers it

How deep it goes
Explains storage, overflow APIs, and dependency trade-offs, but does not develop the broader collection toolbox.
Examples
Demonstrates a 16-byte ArrayVec, a 32-byte ArrayString, and fallible insertion methods.
What it assumes
Assumes basic Rust collection use and explains why embedded programs avoid allocators when capacities are known.
What you can do after
Build bounded vectors and strings, then choose panicking or fallible insertion according to overflow expectations.
How it connects
Connects fixed-capacity collections with Vec, String, heapless, allocators, smallvec, and tinyvec.

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.