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
.
You can't change the size of the array, but you don't need to. You can just allocate a new array that's larger, copy the values you want to keep, delete the original array, and change the member variable to point to the new array. Allocate a new[] array and store it in a temporary pointer.
No. By definition, arrays have a length defined at compile time.
Size of an array Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.
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];
See also:
This should be possible after variable length arrays (VLA) are implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With