變數與資料型別#

Rust 是 靜態型別語言 ,每個變數在編譯時都必須確定其型別。 Rust 編譯器通常能自動推斷型別,不需要每次都手動標注。


1. 變數宣告(let)#

使用 let 關鍵字宣告變數:

1
2
3
4
fn main() {
    let x = 5;
    println!("x = {x}");
}

Rust 的變數預設是 不可變(immutable) 的,一旦賦值就不能再改變:

1
2
3
4
5
fn main() {
    let x = 5;
    // x = 6; // 錯誤!cannot assign twice to immutable variable
    println!("{x}");
}

2. 可變變數(mut)#

若需要可以改變值的變數,要加上 mut 關鍵字:

1
2
3
4
5
fn main() {
    let mut count = 0;
    count = count + 1;
    println!("count = {count}"); // count = 1
}

3. 常數(const)#

常數用 const 宣告, 必須明確標注型別 ,且值不能在執行時計算,只能是編譯時已知的常數表達式:

1
const MAX_SCORE: u32 = 100;

常數可以宣告在任何範圍,包含全域範圍,且 永遠不可變 (不能加 mut)。


4. 遮蔽(Shadowing)#

Rust 允許用同一個名稱重新宣告變數,新的變數會 遮蔽(shadow) 舊的:

1
2
3
4
5
6
fn main() {
    let x = 5;
    let x = x + 1; // 遮蔽前一個 x
    let x = x * 2;
    println!("x = {x}"); // x = 12
}

遮蔽與 mut 不同:遮蔽可以改變型別,mut 則不行。


5. 整數型別#

長度有號無號
8-biti8u8
16-biti16u16
32-biti32u32
64-biti64u64
128-biti128u128
平台相關isizeusize

預設整數型別為 i32

1
2
let a: i32 = -100;
let b: u64 = 9_000_000; // 底線可用來分隔數字,增加可讀性

6. 浮點數型別#

Rust 有兩種浮點數型別,預設為 f64

1
2
let x = 3.14;       // f64
let y: f32 = 2.71;  // f32

7. 布林型別(bool)#

1
2
let is_active: bool = true;
let is_done = false;

8. 字元型別(char)#

Rust 的 char 使用 單引號 ,代表一個 Unicode 純量值(4 個位元組),可以儲存中文、emoji 等:

1
2
3
let letter = 'A';
let emoji = '🦀';
let chinese = '錆';

9. 複合型別:元組(Tuple)#

元組可以將不同型別的值組合在一起,長度固定:

1
2
3
4
5
6
7
fn main() {
    let tup: (i32, f64, bool) = (42, 3.14, true);
    let (x, y, z) = tup; // 解構
    println!("{x}, {y}, {z}");

    println!("{}", tup.0); // 以索引存取,輸出 42
}

10. 複合型別:陣列(Array)#

陣列中的所有元素型別 必須相同 ,長度固定:

1
2
3
4
5
6
7
fn main() {
    let arr = [1, 2, 3, 4, 5];
    let first = arr[0];
    println!("第一個元素:{first}");

    let zeros = [0; 5]; // [0, 0, 0, 0, 0]
}

Reference#

https://doc.rust-lang.org/book/ch03-02-data-types.html