如何创建一个不可变的用户输入数字数组?

How to create an immutable array of user input numbers?

我试图在 rust 中创建一个不可变的用户输入数组,但问题是我必须先初始化数组,如果我初始化数组,我就不能在数组中插入用户输入。

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;
    }
}

错误信息:

   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

在 Rust 中,您不能在不先初始化变量的情况下使用它。但是如果在初始化时你没有最终值,你必须将它声明为 mut:

let mut arr: [i32;5] = [0;5];

然后你自由地初始化arr的值。

如果稍后你想使变量 arr 不可变,你只需编写一个 rebind:

let arr = arr;

附带说明一下,您始终可以重新绑定一个值以使其再次可变:

let mut arr = arr;

还有其他的写法,比如 sub-context 或函数,但或多或​​少是等价的:

let arr = {
    let mut arr: [i32; 5] = [0; 5];
    //add values to arr
    arr
};