# if 表達式

用 `if`／`else if`／`else` 依條件走不同分支；在 Rust 裡 `if` 是會產生值的表達式，而且條件必須是 `bool`。

## 基本形式

`if` 讓程式「如果條件成立就做這件事，否則做那件事」。Rust 的寫法和 C 系語言很像，但有兩個差別：條件不需要小括號，大括號則一定要寫。

### if 與 else

`if 條件 { ... } else { ... }`。`else` 可以省略。`!` 是邏輯「非」，把 `true` 變 `false`。

範例：
```rust
fn main() {
    let temperature = 31;
    if temperature > 30 {
        println!("好熱，開冷氣");
    } else {
        println!("溫度剛好");
    }

    let raining = false;
    if !raining {
        println!("不用帶傘");
    }
}
```

輸出：
```text
好熱，開冷氣
不用帶傘
```

即使分支裡只有一行，大括號也不能省。這消除了 C 語言「少了大括號，第二行其實不在 if 裡」那類錯誤。

### else if 串接多個條件

條件由上往下依序檢查，第一個成立的分支執行後就不再往下看。所以範圍判斷要從最嚴格的條件寫起：下例 80 分會先遇到 `>= 90`（不成立），再遇到 `>= 80`（成立），得到 B。

範例：
```rust
fn grade(score: u32) -> char {
    if score >= 90 {
        'A'
    } else if score >= 80 {
        'B'
    } else if score >= 70 {
        'C'
    } else {
        'F'
    }
}

fn main() {
    for s in [95, 85, 72, 40, 80] {
        println!("{s} 分 → {}", grade(s));
    }
}
```

輸出：
```text
95 分 → A
85 分 → B
72 分 → C
40 分 → F
80 分 → B
```

`grade` 的整個本體就是一個 `if` 表達式，它的值直接成為回傳值，沒有任何 `return`。`else if` 超過三四個時，通常改用 [match](/control-match) 會更清楚。

## if 是表達式

在 Rust 中 `if` 會算出一個值：哪個分支被執行，就取那個分支區塊最後一個表達式的值。這就是其他語言三元運算子 `條件 ? a : b` 的角色，所以 Rust 沒有三元運算子。區塊與表達式的觀念見 [函式與表達式](/basics-functions)。

### 用 if 直接給變數賦值

`let x = if 條件 { 值1 } else { 值2 };`。注意結尾的分號屬於 `let` 陳述式，分支裡的值後面不加分號。`if` 表達式也能接在運算式中，例如 `if ... { 0 } else { 50 } + 10`。

範例：
```rust
fn main() {
    let stock = 0;
    let status = if stock > 0 { "有貨" } else { "缺貨" };
    println!("{status}");

    let n = 7;
    let parity = if n % 2 == 0 { "偶數" } else { "奇數" };
    let fee = if n > 5 { 0 } else { 50 } + 10;
    println!("{n} 是{parity}，運費 {fee}");
}
```

輸出：
```text
缺貨
7 是奇數，運費 10
```

這種寫法讓 `status` 不需要 `mut`、也不會有「忘了在某個分支賦值」的問題。

### 每個分支的型別必須一致

變數只能有一種型別，所以 `if` 的每個分支都必須產生相同型別的值。這段無法編譯：

```rust
fn main() {
    let vip = true;
    let discount = if vip { 0.8 } else { "無折扣" };
    println!("{discount}");
}
```

輸出：
```text
error[E0308]: `if` and `else` have incompatible types
 --> main.rs:3:42
  |
3 |     let discount = if vip { 0.8 } else { "無折扣" };
  |                             ---          ^^^^^^^^ expected floating-point number, found `&str`
  |                             |
  |                             expected because of this
```

想表達「可能有折扣、可能沒有」，可以讓兩邊都回傳數字（沒折扣就是 `1.0`），或改用 `Option<f64>`，見 [Option](/enums-option)。

### 沒有 else 的 if 值是 ()

省略 `else` 時，條件不成立就沒有值可給，所以整個 `if` 的型別只能是 `()`。拿它來賦值會編譯失敗。這段無法編譯：

```rust
fn main() {
    let level = 3;
    let bonus = if level > 5 { 100 };
    println!("{bonus}");
}
```

輸出：
```text
error[E0317]: `if` may be missing an `else` clause
 --> main.rs:3:17
  |
3 |     let bonus = if level > 5 { 100 };
  |                 ^^^^^^^^^^^^^^^---^^
  |                 |              |
  |                 |              found here
  |                 expected integer, found `()`
  |
  = note: `if` expressions without `else` evaluate to `()`
  = help: consider adding an `else` block that evaluates to the expected type
```

補上 `else { 0 }` 即可。只用來「做事」而不取值的 `if`（例如裡面只有 `println!`），不需要 `else`。

## 條件必須是 bool

### 不會自動把數字或物件轉成 bool

C、JavaScript、Python 會把 `0`、空字串、`null` 當成「假」。Rust 不做這種轉換：條件必須是 `bool` 型別。這段無法編譯：

```rust
fn main() {
    let count = 3;
    if count {
        println!("有東西");
    }
}
```

輸出：
```text
error[E0308]: mismatched types
 --> main.rs:3:8
  |
3 |     if count {
  |        ^^^^^ expected `bool`, found integer
```

另外，條件外面多加小括號 `if (count > 0)` 可以編譯，但會得到 `unused_parens` 警告，慣例是不加。

### 寫出明確的比較

把你真正想問的事情寫出來：`!= 0`、`is_empty()`、`is_none()`。這樣讀程式的人一眼就知道條件的意思。`&&` 與 `||` 會短路（short-circuit）：`&&` 左邊為 `false` 時右邊不會執行，所以下例先確認不是空的，才去讀 `items[0]`。

範例：
```rust
fn main() {
    let count = 3;
    let name = String::new();
    let items: Vec<i32> = vec![1, 2];
    let maybe: Option<i32> = None;

    if count != 0 {
        println!("count 不是 0");
    }
    if name.is_empty() {
        println!("name 是空字串");
    }
    if !items.is_empty() && items[0] == 1 {
        println!("第一個元素是 1");
    }
    if maybe.is_none() {
        println!("maybe 沒有值");
    }
}
```

輸出：
```text
count 不是 0
name 是空字串
第一個元素是 1
maybe 沒有值
```

注意：如果把順序寫反成 `items[0] == 1 && !items.is_empty()`，空的 `Vec` 會在索引時 panic。邏輯運算的細節見 [布林與字元](/types-bool-char)。

## if let：同時判斷與取值

### if let 與 let chain

`if let 模式 = 值 { ... }` 在「值符合模式」時執行，並把裡面的資料取出來綁定成變數，最常用來處理 `Option`。2024 edition 可以用 `&&` 把 `if let` 與一般條件串在一起，稱為 let chain（Rust 1.88 起，限 2024 edition）。完整的模式語法見 [模式語法](/control-patterns)。

範例：
```rust
fn main() {
    let input: Option<&str> = Some("42");
    if let Some(text) = input {
        println!("拿到 {text}");
    } else {
        println!("沒有輸入");
    }

    let config: Option<u32> = Some(8);
    if let Some(threads) = config
        && threads > 4
    {
        println!("使用 {threads} 條執行緒");
    }
}
```

輸出：
```text
拿到 42
使用 8 條執行緒
```

## 重點整理

- `if` 條件不加小括號，分支一定要有大括號
- `else if` 由上往下檢查，第一個成立的分支執行後就停止
- `if` 是表達式，可以直接 `let x = if ... { a } else { b };`，取代三元運算子
- 當成值使用時，每個分支型別必須相同，且不能缺少 `else`
- 條件必須是 `bool`，數字、字串、`Option` 都不會自動轉換，要寫出明確的比較
- `if let` 同時判斷與取值；2024 edition 可用 `&&` 串接條件

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
