這裡要討論:
Immutable ➜ 無法被改變(預設)
Mutable ➜ 可以被改變(使用 mut)
直接上程式碼來說明:
以下這段程式碼示範 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
);
}
接下來我們就看看三者的差異性。
let x = 5;
x = 10; // ❌ 編譯錯誤:x 是 immutable
let mut y = 5;
y = 10; // ✅ OK:y 是 mutable
x = 5
x = 10 # ✅ OK,值改了
list1 = [1, 2, 3]
list1.append(4) # ✅ OK,清單被改動
Python 的變數是 名稱指向物件(物件導向)
let x = 5;
x = 10; // ✅ OK:可以改
const y = 5;
y = 10; // ❌ TypeError:const 不能改變值
const list = [1, 2, 3];
list.push(4); // ✅ OK:陣列是 mutable,即使 const 宣告
特性 | 🦀 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 |
mut
上述提到編譯錯誤時,會出現:
error[E0384]: cannot assign twice to immutable variable `a`
此時只要在任一種網頁打上「rust error codes index」,並進入該網頁,就會列出各種錯誤的修正方式,例如此案例中的E0384。