How to set a Rust array length dynamically?

2019-01-26 08:25发布

问题:

I want to create array like this:

let arr = [0; length];

Where length is a usize. But I get this error

E0307
The length of an array is part of its type. For this reason, this length 
must be a compile-time constant.

Is it possible to create array with dynamic length? I want an array, not a Vec.

回答1:

Is it possible to create array with dynamic length?

No. By definition, arrays have a length defined at compile time. A variable (because it can vary) is not known at compile time. The compiler would not know how much space to allocate on the stack to provide storage for the array.

You will need to use a Vec:

let arr = vec![0; length];


标签: arrays rust