How do I initialize an array of vectors?

2019-02-08 04:07发布

问题:

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 type collections::vec::Vec<u8>

回答1:

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<_>>().



回答2:

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.



标签: rust