Matching Values

The match keyword lets you match a value against one or more patterns. The comparisons are done from top to bottom and the first match wins.

模式可以是簡單的值,類似 C 和 C++ 中的 switch

#[rustfmt::skip]
fn main() {
    let input = 'x';
    match input {
        'q'                       => println!("Quitting"),
        'a' | 's' | 'w' | 'd'     => println!("Moving around"),
        '0'..='9'                 => println!("Number input"),
        key if key.is_lowercase() => println!("Lowercase: {key}"),
        _                         => println!("Something else"),
    }
}

The _ pattern is a wildcard pattern which matches any value. The expressions must be exhaustive, meaning that it covers every possibility, so _ is often used as the final catch-all case.

Match can be used as an expression. Just like if, each match arm must have the same type. The type is the last expression of the block, if any. In the example above, the type is ().

A variable in the pattern (key in this example) will create a binding that can be used within the match arm.

A match guard causes the arm to match only if the condition is true.

This slide should take about 10 minutes.

重點:

  • 建議您特別指出某些特定字元在模式中的使用方式

    • | 可做為 or
    • .. 可以視需要展開
    • 1..=5 代表含頭尾的範圍
    • _ 是萬用字元
  • 有些概念比模式本身所允許的更加複雜,如果我們希望簡要地表達這些想法,就必須把配對守衛視為獨立的語法功能。

  • 這與配對分支內的個別 if 運算式不同。分支區塊中的 if 運算式 (位於 => 之後) 會在選取配對分支後發生。即使該區塊內的 if 條件失敗,系統也不會考量原始 match 運算式的其他分支。

  • 只要運算式隸屬於具備 | 的模式之中,就會套用守衛定義的條件。