Rust 變量與可變性

不可變變量

在 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)鍵字一起使用
  • 常量不能被遮蔽
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容