Skip to main content

StackVec

Type Alias StackVec 

Source
pub type StackVec<T, const N: usize, LenT = usize> = VecInner<T, LenT, VecStorageInner<[MaybeUninit<T>; N]>>;
Expand description

A fixed capacity Vec.

§Examples

use heapless::Vec;

// A vector with a fixed capacity of 8 elements allocated on the stack
let mut vec = Vec::<_, 8>::new();
vec.push(1).unwrap();
vec.push(2).unwrap();

assert_eq!(vec.len(), 2);
assert_eq!(vec[0], 1);

assert_eq!(vec.pop(), Some(2));
assert_eq!(vec.len(), 1);

vec[0] = 7;
assert_eq!(vec[0], 7);

vec.extend([1, 2, 3].iter().cloned());

for x in &vec {
    println!("{}", x);
}
assert_eq!(*vec, [7, 1, 2, 3]);

In some cases, the const-generic might be cumbersome. Vec can coerce into a VecView to remove the need for the const-generic:

use heapless::{Vec, VecView};

let vec: Vec<u8, 10> = Vec::from_slice(&[1, 2, 3, 4]).unwrap();
let view: &VecView<_, _> = &vec;

For uncommmon capacity values, or in generic scenarios, you may have to provide the LenT generic yourself.

This should be the smallest unsigned integer type that your capacity fits in, or usize if you don’t want to consider this.

Aliased Type§

pub struct StackVec<T, const N: usize, LenT = usize> { /* private fields */ }