I would like to create an array of vectors like this
let v: [Vec<u8>; 10] = [Vec::new(); 10];
However, the compiler gives me this error:
error: the trait
core::kinds::Copy
is not implemented for the typecollections::vec::Vec<u8>
I would like to create an array of vectors like this
let v: [Vec<u8>; 10] = [Vec::new(); 10];
However, the compiler gives me this error:
error: the trait
core::kinds::Copy
is not implemented for the typecollections::vec::Vec<u8>
You cannot use the [expr; N]
initialisation syntax for non-Copy
types because of Rust’s ownership model—it executes the expression once only, and for non-Copy
types it cannot just copy the bytes N times, they must be owned in one place only.
You will need to either:
Write it out explicitly ten times: let v: [Vec<u8>; 10] = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]]
, or
Use something like a vector instead of the array: std::iter::repeat(vec![]).take(10).collect::<Vec<_>>()
.
You could use the Default trait to initialize the array with default values:
let array: [Vec<u8>; 10] = Default::default();
See this playground for a working example.