在Rust书籍的第三章节变量和可变性中,我们通过几次迭代来展示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
有趣的是,尽管我们第一次将
x
绑定到5
时没有调用let
而是调用了mut
,但此代码也会产生上述一对行作为输出:fn main() {
let mut x = 5;
println!("The value of x is {}", x);
x = 6;
println!("The value of x is {}", x);
}
变量在不被重新分配时(实际上并未)如何保护似乎与 Rust 默认保护不可变变量绑定的值的目标相矛盾。来自同一章节(还包含 Shadowing 部分):
当我们尝试更改先前指定为不可变的值时,重要的是我们获得编译时错误,因为这种情况可能会导致错误。如果我们代码的一部分操作假设一个值永远不会改变,而我们代码的另一部分更改了该值,那么第一部分代码可能无法执行其设计目的。这种错误的原因可能在事后难以跟踪,特别是当第二段代码只有在某些时候更改值时。
在 Rust 中,编译器保证当您声明一个值不会更改时,它确实不会更改。这意味着在读写代码时,您不必跟踪值可能更改的方式和位置。因此,您的代码更容易理解。
如果我可以通过足够无辜的调用let
来使我的不可变x
的这个重要特性被规避,那么我为什么需要mut
?是否有一种真正且严肃的方法可以使x
不可变,以便没有let x
可以重新分配其值?