变量与可变性
let/let mut、不可变默认、const/static、shadowing 遮蔽
变量与可变性
Rust 变量默认不可变——这是安全哲学的体现。mut 显式声明可变,shadowing 允许重新绑定。
学完本章你将: 掌握 let/let mut、不可变默认、const、shadowing。
不可变与可变
rust
fn main() {
let x = 5; // 不可变
// x = 6; // ❌ 编译错误!
let mut y = 10; // 可变
y = 20; // ✅
println!("y = {}", y);
}
常量 const
rust
const MAX_POINTS: u32 = 100_000; // 必须标注类型
const PI: f64 = 3.1415926535;
// const 是编译期常量——全局、内联
// let 是运行时变量
Shadowing(遮蔽)
rust
fn main() {
let x = 5;
let x = x + 1; // 遮蔽——新的 x
let x = x * 2; // 再次遮蔽
// 每次 let 创建一个新变量——类型可以不同
let spaces = " ";
let spaces = spaces.len(); // &str → usize
println!("{}", x); // 12
}
| let mut | Shadowing | |
|---|---|---|
| 修改 | 同一变量 | 新变量 |
| 类型 | 不能变 | 可以变 |
| 不可变性 | 打破 | 保持 |