变量绑定默认是不可变的,但加上 mut
修饰语后变量就可以改变。
fn main() { let _immutable_binding = 1; let mut mutable_binding = 1; println!("Before mutation: {}", mutable_binding); // 正确代码 mutable_binding += 1; println!("After mutation: {}", mutable_binding); // 错误! _immutable_binding += 1; // 改正 ^ 将此行注释掉 }
cargo build Compiling own v0.1.0 (/data2/rust/mut) error[E0384]: cannot assign twice to immutable variable `_immutable_binding` --> src/main.rs:13:5 | 2 | let _immutable_binding = 1; | ------------------ | | | first assignment to `_immutable_binding` | help: make this binding mutable: `mut _immutable_binding` ... 13 | _immutable_binding += 1; | ^^^^^^^^^^^^^^^^^^^^^^^ cannot assign twice to immutable variable error: aborting due to previous error For more information about this error, try `rustc --explain E0384`. error: could not compile `own`. To learn more, run the command again with --verbose.