Reputation: 1329
I need structures with fixed maximum size, so the obvious choice seem to be arrayvec crate. However, I'm stuck when ArrayVec
is a member of a structure that later needs to be partially initialised:
use arrayvec::ArrayVec; // 0.4.7
#[derive(Debug)]
struct Test {
member_one: Option<u32>,
member_two: ArrayVec<[u16; 5]>,
}
pub fn main() {
let mut test = Test {
member_one: Some(45678),
member_two: [1, 2, 3], // <- What to do here to initialise only 3 elements?
};
print!("{:?}", test);
}
I'd like to initialise the first three elements of the ArrayVec
as it's perfectly capable of holding any number of elements from zero to 5 (in my example), but I can't figure out how to do it.
Upvotes: 1
Views: 288
Reputation: 58735
You can collect into an ArrayVec
from an iterator:
let mut test = Test {
member_one: Some(45678),
member_two: [1, 2, 3].into_iter().collect(),
};
Upvotes: 3
Reputation: 430961
ArrayVec
does not offer a one-step method to do this. Instead, create the ArrayVec
and then add values to it, in any of the ways you can add values:
let mut member_two = ArrayVec::new();
member_two.extend([1, 2, 3].iter().cloned());
let test = Test {
member_one: Some(45678),
member_two,
};
Upvotes: 1