How do I initialize an array of vectors?

前端 未结 3 1903
我在风中等你
我在风中等你 2021-01-01 10:05

I would like to create an array of vectors:

fn main() {
    let v: [Vec; 10] = [Vec::new(); 10];
}

However, the compiler gives me t

3条回答
  •  醉话见心
    2021-01-01 10:31

    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; 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::>().

    See also:

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

提交回复
热议问题