不可變變量
在 Rust 中變量默認(rèn)是不可變的
使用 let 定義 x = 5, 然后將 6 賦值給 x,這樣是不能通過(guò)編譯的。
src/main.rs
fn main() {
let x = 5;
x = 6;
}
執(zhí)行 rustc main.rs 會(huì)得到如下錯(cuò)誤:
error[E0384]: cannot assign twice to immutable variable `x`
--> main.rs:3:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: make this binding mutable: `mut x`
3 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0384`.
遮蔽 (shadowing)
可以再次使用 let 遮蔽同名變量
src/main.rs
fn main() {
let x = 5;
let x = 6;
let x = "";
}
可變變量
要聲明可變變量則需要使用 mut 關(guān)鍵字
fn main() {
let mut x = 5;
x = 6;
}
常量
使用 const 關(guān)鍵字可以聲明常量
fn main() {
const MAX_POINTS: u32 = 100_000;
}
不可變變量和常量的區(qū)別如下:
- 常量必須指定類(lèi)型
- 常量不能和 mut 關(guān)鍵字一起使用
- 常量不能被遮蔽