我很惊讶地发现以下程序将愉快地编译并运行(使用“ cargo 1.42.0(86334295e 2020-01-31)。”,输出:
5k
不声明为mut的变量x不仅会重新分配,而且会以其他类型重新分配。有什么理由允许您这样做?
fn main() {
let x = 5;
println!("{}", x);
let t: (i32, f64, char) = (2, 3.14, 'k');
let (_,_,x) = t;
println!("{}", x);
}
这称为“阴影变量”
([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