分支(Branch)#

分支讓程式根據條件的結果,決定要執行哪一段程式碼。 Rust 提供 if 表達式與 match 表達式兩種主要的分支機制。


1. if 表達式#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
fn main() {
    let number = 7;

    if number < 10 {
        println!("數字小於 10");
    } else if number == 10 {
        println!("數字等於 10");
    } else {
        println!("數字大於 10");
    }
}

Rust 的 if 條件 必須是 bool 型別 ,不像其他語言會自動將整數轉為布林:

1
2
3
4
let n = 1;
if n { // 錯誤!條件必須是 bool,而不是 i32
    println!("one");
}

2. if 作為表達式#

Rust 中 if表達式(expression) ,可以回傳值:

1
2
3
4
5
fn main() {
    let condition = true;
    let number = if condition { 5 } else { 10 };
    println!("number = {number}"); // number = 5
}

兩個分支必須回傳 相同型別 的值,否則編譯器會報錯。


3. match 表達式#

match 是 Rust 強大的模式匹配機制,逐一比對每個 分支(arm)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fn main() {
    let coin = 25u32;

    let name = match coin {
        1  => "一分錢",
        5  => "五分錢",
        10 => "十分錢",
        25 => "二十五分錢",
        _  => "其他",   // _ 是萬用模式,匹配所有其他情況
    };

    println!("{name}");
}

match 必須 窮舉所有可能性 ,否則編譯器會報錯。


4. match 搭配枚舉#

match 與枚舉(Enum)搭配使用非常強大:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
enum Direction {
    North,
    South,
    East,
    West,
}

fn describe(dir: Direction) {
    match dir {
        Direction::North => println!("向北"),
        Direction::South => println!("向南"),
        Direction::East  => println!("向東"),
        Direction::West  => println!("向西"),
    }
}

5. match 綁定值#

match 的分支可以綁定匹配到的值:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
enum Coin {
    Quarter(String),
    Other(u32),
}

fn value(coin: Coin) {
    match coin {
        Coin::Quarter(state) => println!("25分錢,州名:{state}"),
        Coin::Other(amount)  => println!("面額:{amount}"),
    }
}

6. if let#

當只在乎某一個匹配情況、不想寫完整 match 時,可以使用 if let

1
2
3
4
5
6
7
8
9
fn main() {
    let some_value: Option<i32> = Some(42);

    if let Some(v) = some_value {
        println!("值是 {v}");
    } else {
        println!("沒有值");
    }
}

if let 語法更簡潔,但會放棄 match 的窮舉檢查。


7. while let#

類似 if letwhile let 讓迴圈在模式匹配成功時持續執行:

1
2
3
4
5
6
7
fn main() {
    let mut stack = vec![1, 2, 3]; // Vec 集合將在 CH13 詳細介紹

    while let Some(top) = stack.pop() {
        println!("{top}");
    }
}

Reference#

https://doc.rust-lang.org/book/ch06-02-match.html