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
