let 声明变量mut 关键字const 与变量的区别Rust 中变量默认不可变:
fn main() { let x = 5; println!("x = {}", x); // x = 6; // 错误:cannot assign twice to immutable variable }
这种设计让代码更安全,更容易推理。
fn main() { let mut x = 5; println!("x = {}", x); x = 6; println!("x = {}", x); }
mut 加在绑定名前,表示该绑定指向的内容可以被修改。
常量使用 const 声明,必须标注类型,且值必须能在编译期确定:
const MAX_POINTS: u32 = 100_000;
常量与不可变变量的区别:
- 常量不能加 mut。
- 常量必须标注类型。
- 常量在整个程序生命周期内有效,而变量有作用域。
fn main() { let x = 5; let x = x + 1; // 新 x 遮蔽了旧 x let x = x * 2; println!("x = {}", x); // 12 }
遮蔽与 mut 的区别:
- let x = x + 1 创建了一个新的绑定。
- 遮蔽可以改变类型,而 mut 不能:
let spaces = " "; let spaces = spaces.len(); // 类型从 &str 变成 usize
let x = 5; 改成 x = 6;,观察编译错误。mut 重写,让 x 从 5 变到 10。x = 5 -> x = x + 3 -> x = x * 2。PI: f64 = 3.14159。let 默认不可变,mut 允许修改。const 是编译期常量,必须标注类型。_ 前缀用于有意忽略的变量。