为什么这个 Rust 程序忽略了不变性 [英] Why does this Rust program ignore immutability
问题描述
我有以下 Rust 程序,我希望它会导致编译错误,因为 x
稍后被重新分配.但它遵守并提供输出.为什么?
I have the following Rust program and I expect it to result in an compilation error since x
is reassigned later. But it complies and gives output. Why?
fn main() {
let (x, y) = (1, 3);
println!("X is {} and Y is {}", x, y);
let x: i32 = 565;
println!("Now X is {}", x);
}
推荐答案
Rust 实际上可以让你隐藏块中的其他变量,所以 let x: i32 = 565;
定义了一个 new 变量 x
隐藏了之前定义的 let (x,y) = (1,3);
的 x
.请注意,您甚至可以重新定义 x
以具有不同的类型,因为第二个 x
是一个全新的变量!
Rust actually lets you shadow other variables in a block, so let x: i32 = 565;
is defining a new variable x
that shadows the x
defined earlier with let (x,y) = (1,3);
. Note that you could even have redefined x
to have a different type since the second x
is a whole new variable!
fn main(){
let x = 1;
println!("Now X is {}",x);
let x = "hi";
println!("Now X is {}",x);
}
这个reddit 线程更详细地说明了为什么会这样有用.提到的两件事似乎很有趣:
This reddit thread goes into more detail about why this is useful. The two things that are mentioned that seem interesting are:
对于获取变量所有权但返回另一个相同类型的变量的操作,有时将返回的变量重新定义为具有相同的名称看起来不错".来自 此处:
let iter = vec.into_iter();
let iter = modify(iter);
let iter = double(iter);
或者使变量不可变:
Or to make a variable immutable:
let mut x;
// Code where `x` is mutable
let x = x;
// Code where `x` is immutable
这篇关于为什么这个 Rust 程序忽略了不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!