How do I initialize an array of vectors?

You can only instantiate arrays in such fashion if the type implements the Copy trait. This trait is only for types that can be copied byte by byte (and since vector points to heap, it can't be implemented).

One answer to this problem is the array_init crate that provides much more general way of initializing arrays in complicated fashion.

let multi: [Vec<u8>; 10] = array_init::array_init(|_| vec![0; 24]);

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.


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:

  1. Write it out explicitly ten times: let v: [Vec<u8>; 10] = [vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![], vec![]], or

  2. Use something like a vector instead of the array: std::iter::repeat(vec![]).take(10).collect::<Vec<_>>().

See also:

  • Initialize a large, fixed-size array with non-Copy types

Tags:

Arrays

Rust