if 表達式

最後更新


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

基本形式


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

if 與 else


if 條件 { ... } else { ... }。else 可以省略。! 是邏輯「非」,把 true 變 false。
範例:
  1. fn main() {
  2. let temperature = 31;
  3. if temperature > 30 {
  4. println!("好熱,開冷氣");
  5. } else {
  6. println!("溫度剛好");
  7. }
  8. let raining = false;
  9. if !raining {
  10. println!("不用帶傘");
  11. }
  12. }

輸出:
  1. 好熱,開冷氣
  2. 不用帶傘

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

else if 串接多個條件


條件由上往下依序檢查,第一個成立的分支執行後就不再往下看。所以範圍判斷要從最嚴格的條件寫起:下例 80 分會先遇到 >= 90(不成立),再遇到 >= 80(成立),得到 B。
範例:
  1. fn grade(score: u32) -> char {
  2. if score >= 90 {
  3. 'A'
  4. } else if score >= 80 {
  5. 'B'
  6. } else if score >= 70 {
  7. 'C'
  8. } else {
  9. 'F'
  10. }
  11. }
  12. fn main() {
  13. for s in [95, 85, 72, 40, 80] {
  14. println!("{s} 分 → {}", grade(s));
  15. }
  16. }

輸出:
  1. 95 分 → A
  2. 85 分 → B
  3. 72 分 → C
  4. 40 分 → F
  5. 80 分 → B

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

if 是表達式


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

用 if 直接給變數賦值


let x = if 條件 { 值1 } else { 值2 };。注意結尾的分號屬於 let 陳述式,分支裡的值後面不加分號。if 表達式也能接在運算式中,例如 if ... { 0 } else { 50 } + 10。
範例:
  1. fn main() {
  2. let stock = 0;
  3. let status = if stock > 0 { "有貨" } else { "缺貨" };
  4. println!("{status}");
  5. let n = 7;
  6. let parity = if n % 2 == 0 { "偶數" } else { "奇數" };
  7. let fee = if n > 5 { 0 } else { 50 } + 10;
  8. println!("{n} 是{parity},運費 {fee}");
  9. }

輸出:
  1. 缺貨
  2. 7 是奇數,運費 10

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

每個分支的型別必須一致


變數只能有一種型別,所以 if 的每個分支都必須產生相同型別的值。這段無法編譯:
  1. fn main() {
  2. let vip = true;
  3. let discount = if vip { 0.8 } else { "無折扣" };
  4. println!("{discount}");
  5. }

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

想表達「可能有折扣、可能沒有」,可以讓兩邊都回傳數字(沒折扣就是 1.0),或改用 Option<f64>,見 Option。

沒有 else 的 if 值是 ()


省略 else 時,條件不成立就沒有值可給,所以整個 if 的型別只能是 ()。拿它來賦值會編譯失敗。這段無法編譯:
  1. fn main() {
  2. let level = 3;
  3. let bonus = if level > 5 { 100 };
  4. println!("{bonus}");
  5. }

輸出:
  1. error[E0317]: `if` may be missing an `else` clause
  2. --> main.rs:3:17
  3. |
  4. 3 | let bonus = if level > 5 { 100 };
  5. | ^^^^^^^^^^^^^^^---^^
  6. | | |
  7. | | found here
  8. | expected integer, found `()`
  9. |
  10. = note: `if` expressions without `else` evaluate to `()`
  11. = 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 型別。這段無法編譯:
  1. fn main() {
  2. let count = 3;
  3. if count {
  4. println!("有東西");
  5. }
  6. }

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

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

寫出明確的比較


把你真正想問的事情寫出來:!= 0、is_empty()、is_none()。這樣讀程式的人一眼就知道條件的意思。&& 與 || 會短路(short-circuit):&& 左邊為 false 時右邊不會執行,所以下例先確認不是空的,才去讀 items[0]。
範例:
  1. fn main() {
  2. let count = 3;
  3. let name = String::new();
  4. let items: Vec<i32> = vec![1, 2];
  5. let maybe: Option<i32> = None;
  6. if count != 0 {
  7. println!("count 不是 0");
  8. }
  9. if name.is_empty() {
  10. println!("name 是空字串");
  11. }
  12. if !items.is_empty() && items[0] == 1 {
  13. println!("第一個元素是 1");
  14. }
  15. if maybe.is_none() {
  16. println!("maybe 沒有值");
  17. }
  18. }

輸出:
  1. count 不是 0
  2. name 是空字串
  3. 第一個元素是 1
  4. maybe 沒有值

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

if let:同時判斷與取值


if let 與 let chain


if let 模式 = 值 { ... } 在「值符合模式」時執行,並把裡面的資料取出來綁定成變數,最常用來處理 Option。2024 edition 可以用 && 把 if let 與一般條件串在一起,稱為 let chain(Rust 1.88 起,限 2024 edition)。完整的模式語法見 模式語法。
範例:
  1. fn main() {
  2. let input: Option<&str> = Some("42");
  3. if let Some(text) = input {
  4. println!("拿到 {text}");
  5. } else {
  6. println!("沒有輸入");
  7. }
  8. let config: Option<u32> = Some(8);
  9. if let Some(threads) = config
  10. && threads > 4
  11. {
  12. println!("使用 {threads} 條執行緒");
  13. }
  14. }

輸出:
  1. 拿到 42
  2. 使用 8 條執行緒

重點整理


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

資料來源