How do I initialize an array of vectors?

2019-02-08 04:28发布

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>

标签: rust
2条回答
Anthone
2楼-- · 2019-02-08 04:46

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.

查看更多
成全新的幸福
3楼-- · 2019-02-08 04:57

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

查看更多
登录 后发表回答