I am trying to create an array of the same length as a vector, in rust but I keep getting errors.
//my code
fn main() {
let v = vec![1,2,3];
let len = v.len();
let a: [i32; len] = [0; len];
println!("{:?}", a);
}
The Error Message :
Compiling playground v0.0.1 (/playground)
error[E0435]: attempt to use a non-constant value in a constant
--> src/main.rs:4:18
|
3 | let len = v.len();
| ------- help: consider using `const` instead of `let`: `const len`
4 | let a: [i32; len] = [0; len];
| ^^^ non-constant value
error[E0435]: attempt to use a non-constant value in a constant
--> src/main.rs:4:29
|
3 | let len = v.len();
| ------- help: consider using `const` instead of `let`: `const len`
4 | let a: [i32; len] = [0; len];
| ^^^ non-constant value
For more information about this error, try `rustc --explain E0435`.
error: could not compile `playground` due to 2 previous errors
If I declare len as a const
fn main() {
let v = vec![1,2,3];
const len: usize = v.len();
let a: [i32; len] = [0; len];
println!("{:?}", a);
}
I get this error:
Compiling playground v0.0.1 (/playground)
error[E0435]: attempt to use a non-constant value in a constant
--> src/main.rs:3:24
|
3 | const len: usize = v.len();
| --------- ^ non-constant value
| |
| help: consider using `let` instead of `const`: `let len`
For more information about this error, try `rustc --explain E0435`.
error: could not compile `playground` due to previous error
Why exactly is the above code giving me an error. In other languages I can assign the length of a vector or arraylist to a constant variable. Even though the length of a vec is mutable but the length of vec at the time of assignment must have been a constant value. So why am I getting this error?
And also how can I create an array of the same length as vector in rust?