可以使用解构重新分配 RUST 中的不可变变量吗?

Immutable variables in RUST can be reassigned using destructuring?

我很惊讶地发现下面的程序可以愉快地编译和运行(使用"cargo 1.42.0 (86334295e 2020-01-31)."),输出:

5 k

没有声明为mut的变量x不仅被重新赋值,而且被重新赋值了不同的类型。 有什么理由允许您这样做吗?

fn main() {

    let x = 5;

    println!("{}", x);

    let t: (i32, f64, char) = (2, 3.14, 'k');

    let (_,_,x) = t;

    println!("{}", x);

}

这叫"shadowing a variable"

(https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html#shadowing)

也可以简单的表示为:

let x = 5;
let x = 'k';

其实经常派上用场。例如,您可以在使用完其初始分配值后重用标识符:

let two_times_five = 2 * 5; // type i32
let two_times_five = two_times_five.to_string(); // type String

编译器仍然会强制强类型;在重新定义之前访问 two_times_five 将访问 i32,之后访问将访问 String。

有时您不希望变量可变,但有时您又想为其分配不同的值。使用变量阴影而不是 let mut 意味着您知道变量在其定义之间不会更改,无论它被传递到什么函数或调用它的方法。