Reputation: 7386
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
.
Upvotes: 85
Views: 109368
Reputation: 109
(I'm a Rust noob myself, but since this question is a top result and I had to learn this from a blog post:)
One way you can have compile-time arrays with an unknown size (like in Java) is by using constant generics:
fn my_array_function<const LEN: usize>(arr: [i32; LEN], arr2: [i32; LEN]) { ... }
This is useful when you're asserting that no matter what the size is, as long as it's consistent when the function is called, the function will perform the same way regardless of the value.
You can also use this value later in the code, like for i in 0..LEN { ... }
to iterate through the array, or let new_arr = [0; LEN]
to make a new array of the same size as the input.
It's basically the same thing as myFunction(size_t N, int[N] arr) { ... }
but with type-safety.
Upvotes: 4
Reputation: 1021
This should be possible after variable length arrays (VLA) are implemented.
Upvotes: 16
Reputation: 432109
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:
Upvotes: 110