iT邦幫忙

3

二、三天學一點點 Rust:來!那些變數們(4)

  • 分享至 

  • xImage
  •  

這裡要討論:

  • Immutable ➜ 無法被改變(預設)

  • Mutable ➜ 可以被改變(使用 mut)

直接上程式碼來說明:

🦀 Rust:不可變變數(Immutable)示範

以下這段程式碼示範 Rust 中變數的不可變性(immutable),若未加上 mut,變數預設是不能被改變的。

fn main() {
    let a: i32 = 50;
    let b: i32 = 30;
    let total = a + b;
    println!(
        "The numbers are {} and {}. Their total is {}.",
        a, b, total
    );

    a = 20; // ❌ 錯誤:a 是不可變的(immutable)
    
    println!(
        "The numbers are {} and {}. Their total is {}.",
        a, b, total
    );
}

由上面可知:
在 let a: i32 = 50; 中,a 預設是不可變(immutable)。
後面的 a = 20; 會嘗試修改 a 的值,因此被 Rust 拒絕。

因此編輯上述程式碼,Rust 編譯器會出現錯誤:

error[E0384]: cannot assign twice to immutable variable `a`

使用可變變數

如果你希望程式碼正確,就必須加上mut:

fn main() {
    let mut a: i32 = 50;
    let b: i32 = 30;
    let mut total = a + b;
    println!(
        "There is number {} and {}. And total number is {}.",
        a, b, total
    );

    a = 20;
    total = a + b;

    println!(
        "There is number {} and {}. And total number is {}.",
        a, b, total
    );
}

🔍 Rust vs Python vs JavaScript:變數可變性的差異

接下來我們就看看三者的差異性。

🦀 Rust:預設不可變(immutable)

let x = 5;
x = 10; // ❌ 編譯錯誤:x 是 immutable

let mut y = 5;
y = 10; // ✅ OK:y 是 mutable

🐍 Python:預設可變(mutable)?其實不是這麼簡單!

x = 5
x = 10  # ✅ OK,值改了

list1 = [1, 2, 3]
list1.append(4)  # ✅ OK,清單被改動

Python 的變數是 名稱指向物件(物件導向)

  • 基本型別(int, str, float)是 immutable
  • 容器型別(list, dict)是 mutable
    ✅ 雖然你可以重新賦值,但值本身可能是 immutable(例如字串)

🌐 JavaScript:預設 mutable,除非用 const

let x = 5;
x = 10; // ✅ OK:可以改

const y = 5;
y = 10; // ❌ TypeError:const 不能改變值

const list = [1, 2, 3];
list.push(4); // ✅ OK:陣列是 mutable,即使 const 宣告
  • let ➜ 可變
  • const ➜ 不可重新指定,但內容仍可能是可變的
    ✅ 基本型別與物件處理方式不同

🧠 Rust vs Python vs JavaScript:變數可變性比較表

特性 🦀 Rust 🐍 Python 🌐 JavaScript
預設是否可變 ❌ 不可變(需要加 mut ✅ 可重新指派變數 let 預設可變
是否可宣告不可變 ✅ 使用 let(不加 mut ❌ 不支援(可用習慣或 decorator) ✅ 使用 const
基本型別行為 immutable(如 i32, f64 immutable(如 int, str immutable(如 number, string
容器型別是否可變 取決於是否使用 mut ✅ list, dict 等是 mutable ✅ array, object 等是 mutable

✅ 總結:

  • Rust 預設變數是 immutable,要改變必須加上 mut
  • Python 與 JavaScript 預設較「彈性」,可以隨時改值,但不一定更安全
  • Rust 的設計是為了提升安全性與意圖明確性

✅ 補充:

上述提到編譯錯誤時,會出現:

error[E0384]: cannot assign twice to immutable variable `a`

此時只要在任一種網頁打上「rust error codes index」,並進入該網頁,就會列出各種錯誤的修正方式,例如此案例中的E0384。


尚未有邦友留言

立即登入留言