mut
1234567
// 可变变量let mut x = 5;x = 6; // ✅ 可以修改// 不可变变量let y = 10;// y = 11; // ❌ 错误:不可修改
const
12
// 常量定义const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;
使用 let 重复声明同名变量时,新变量会 遮蔽 旧变量。
let
123456789
fn main() { let x = 5; let x = x + 1; // 新的 x 遮蔽旧的 x=5 { let x = x * 2; // 仅在当前作用域生效,不会遮蔽前面的x = x + 1 println!("The value of x in the inner scope is: {x}"); // 输出 12 } println!("The value of x is: {x}"); // 输出 6}
// 使用 mut:错误let mut spaces = " ";// spaces = spaces.len(); // ❌ 类型不匹配,&str 不能赋值为 usize// 使用遮蔽:正确let spaces = " ";let spaces = spaces.len(); // ✅ 类型从 &str → usize
Hooray!变量和可变性学习完成!!!