在Chapter 3 of the Rust BookVariables and Mutability中,我们对这个主题进行了几次迭代,以演示Rust中变量的默认、不变行为:
fn main() {
let x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
输出:
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: make this binding mutable: `mut x`
3 | println!("The value of x is {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
然而,由于Rust接受了shadowing个变量,我们可以简单地这样做来更改"不可变"x
的值:
fn main() {
let x = 5;
println!("The value of x is {}", x);
let x = 6;
println!("The value of x is {}", x);
}
哪些输出(跳过详细信息):
The value of x is 5
The value of x is 6
有趣的是,这段代码还生成了上述两行作为输出,尽管我们不调用let
,而是在x
第一次绑定到5
时调用mut
:
fn main() {
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
变量如何(并非真正)避免重新分配的模糊性,似乎与保护绑定到不可变(默认情况下)变量的值的既定目标背道而驰.来自同一章(也包含第Shadowing节):
重要的是,当我们试图
在Rust中,编译器保证当您声明
如果我能让我的不变性x
的这一重要特性被一个足够天真的let
调用所取代,为什么我需要mut
呢?你们真的有办法让x
不可变,这样就没有let x
可以重新分配它的值了吗?