Rust语言编程实例100题-073
题目:Rust变量冻结。当数据被相同的名称不变地绑定时,它还会冻结(freeze)。在不可变绑定超出作用域之前,无法修改已冻结的数据。变量冻结应该算作Rust的特性了。编写程序练习Rust的变量冻结
程序分析:作用域外和作用域内定义同名变量,运行看结果。
知识点:变量冻结
参考程序代码:
fn main() {
let mut mut_int = 3;
{
let mut_int = 5;
// 下面代码如果不注释,则会发生错误
mut_int = 6;
}
mut_int = 9;
dbg!(mut_int);
}
程序执行结果:
error[E0384]: cannot assign twice to immutable variable `mut_int`
--> src\test.rs:742:9
|
741 | let mut_int = 5;
| -------
| |
| first assignment to `mut_int`
| help: make this binding mutable: `mut mut_int`
742 | mut_int = 6;
| ^^^^^^^^^^^ cannot assign twice to immutable variable
Process finished with exit code 0