0

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
2
  • 2
    What if you add mut where the error suggests? If you really want arr to be immutable you can write let arr = arr; later. Is that what you want? Commented Feb 18, 2022 at 20:31
  • Let me extend that into an answer... Commented Feb 18, 2022 at 20:37

1 Answer 1

4

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
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.