I am trying to create an immutable array of user input in rust but the problem is that I have to initialize the array first, and if I initialize the array I cannot insert user inputs in the array.
fn main() {
//error: If I don't initialize the array then it throws and error.
let arr: [i32;5] = [0;5];
for i in 0..5 {
// let i be the user input for now
// if I do initialize the array I cannot reassign the array elements because of immutability
arr[i] = i as i32;
}
}
Error Message:
Compiling playground v0.0.1 (/playground)
error[E0594]: cannot assign to `arr[_]`, as `arr` is not declared as mutable
--> src/main.rs:7:9
|
3 | let arr: [i32;5] = [0;5];
| --- help: consider changing this to be mutable: `mut arr`
...
7 | arr[i] = i as i32;
| ^^^^^^^^^^^^^^^^^ cannot assign
For more information about this error, try `rustc --explain E0594`.
error: could not compile `playground` due to previous error
CodePudding user response:
In Rust you cannot use a variable without initializing it first. But if at initialization time you do not have the final values, you have to declare it as mut
:
let mut arr: [i32;5] = [0;5];
And then you initialize the values of arr
freely.
If later you want to make the variable arr
immutable you just write a rebind:
let arr = arr;
As a side note you can always rebind a value to make it mutable again:
let mut arr = arr;
There are other ways to write that, like a sub-context or a function, but are more or less equivalent:
let arr = {
let mut arr: [i32; 5] = [0; 5];
//add values to arr
arr
};