主题
变量
let 创建绑定,默认不可变。mut 允许原地再赋值。类型通常可推断,函数边界和 const / static 必须显式标注。
rust
let count = 1;
let mut total = 0;
total += count;重新 let 同一个名字是遮蔽(shadowing):新绑定可以改类型,旧绑定结束。mut 只能改值,不能改类型。
rust
let spaces = " ";
let spaces = spaces.len(); // usize,前一个 &str 被遮蔽作用域
绑定在声明它的块结束时失效。内层块可以遮蔽外层同名绑定,离开内层后外层仍在。
rust
let x = 1;
{
let x = 2;
assert_eq!(x, 2);
}
assert_eq!(x, 1);const 与 static
const | static | |
|---|---|---|
| 时机 | 编译期常量,内联到使用处 | 程序生命周期内有固定地址 |
| 可变 | 不可变 | static mut 存在,但需要 unsafe |
| 类型 | 必须显式 | 必须显式 |
rust
const MAX_RETRY: u32 = 3;
static APP_NAME: &str = "demo";const 用于没有身份的常量值。需要固定内存地址或跨线程共享只读数据时用 static。可变全局状态不是默认方案。
