Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

else if

本集目標

else if 處理多個條件分支——不只二選一,還能三選一、四選一。

正文

上一集學的 if...else 只能處理「二選一」。但如果有更多情況呢?比如成績分等第:A、B、C、F……這時候就需要 else if

範例:成績等第

fn main() {
    let score = 85;

    if score >= 90 {
        println!("A");
    } else if score >= 80 {
        println!("B");
    } else if score >= 70 {
        println!("C");
    } else {
        println!("F");
    }
}

它是怎麼判斷的?

Rust 會從上到下,一個一個條件去看:

  1. score >= 90?85 >= 90?不是,跳過。
  2. score >= 80?85 >= 80?是!印 “B”,然後結束。
  3. 後面的都不看了。

這很重要:一旦某個條件成立,後面的都會被跳過

試試其他分數

  • score = 95 → 印 “A”
  • score = 73 → 印 “C”
  • score = 50 → 印 “F”(前面全部不成立,走到 else

結構

if 條件1 {
    ...
} else if 條件2 {
    ...
} else if 條件3 {
    ...
} else {
    ...(以上都不成立時)
}

你可以放任意多個 else if,最後的 else 是選擇性的(但通常建議加上去,以防漏掉什麼情況)。

重點整理

  • else if 可以處理多個條件分支,不只二選一
  • Rust 從上到下檢查條件,第一個成立的就執行,後面全部跳過
  • 最後的 else 是選擇性的,用來處理「以上條件都不成立」的情況