Matching Values
match キーワードを使用すると、1 つ以上のパターンに対して値を照合できます。上から順に照合が行われ、最初に一致したパターンのみが実行されます。
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.
一致を式として使用できます。if と同様に、各マッチアームは同じ型にする必要があります。型は、ブロックの最後の式です(存在する場合)。上記の例では、型は () です。
パターンの変数(この例では key)により、マッチアーム内で使用できるバインディングが作成されます。
マッチガードにより、条件が true の場合にのみアームが一致します。
キーポイント:
-
特定の文字がパターンでどのように使用されるかを説明します。
|をorとして指定する..は必要に応じて展開できる1..=5は 5 を含む範囲を表す_はワイルドカードを表す
-
パターンのみでは表現できない複雑な概念を簡潔に表現したい場合、独立した構文機能であるマッチガードは重要かつ必要です。
-
マッチガードは、マッチアーム内の個別の
if式とは異なります。分岐ブロック内(=>の後)のif式は、マッチアームが選択された後に実行されます。そのブロック内でif条件が満たされなかった場合、元のmatch式の他のアームは考慮されません。 -
ガードで定義された条件は、
|が付いたパターン内のすべての式に適用されます。
More To Explore
-
Another piece of pattern syntax you can show students is the
@syntax which binds a part of a pattern to a variable. For example:#![allow(unused)] fn main() { let opt = Some(123); match opt { outer @ Some(inner) => { println!("outer: {outer:?}, inner: {inner}"); } None => {} } }In this example
innerhas the value 123 which it pulled from theOptionvia destructuring,outercaptures the entireSome(inner)expression, so it contains the fullOption::Some(123). This is rarely used but can be useful in more complex patterns.