How to set the length of a Rust array dynamically?

I want to create an array as follows:

let arr = [0; length]; 

Where the length is 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 an array with dynamic length? I want an array, not Vec .

+11
source share
1 answer

Is it possible to create an array with dynamic length?

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

You will need to use Vec :

 let arr = vec![0; length]; 

See also:

+23
source

Source: https://habr.com/ru/post/1240186/


All Articles