snippetrustCritical
How to set a Rust array length dynamically?
Viewed 0 times
arrayhowsetdynamicallyrustlength
Problem
I want to create array like this:
Where length is a
Is it possible to create array with dynamic length? I want an array, not a
let arr = [0; length];Where length is a
usize. But I get this errorE0307
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.Solution
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
See also:
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];See also:
- Is it possible to control the size of an array using the type parameter of a generic?
Code Snippets
let arr = vec![0; length];Context
Stack Overflow Q#34684261, score: 112
Revisions (0)
No revisions yet.