Rust•条件分岐
Rust の網羅的 Match パターンマッチングと式による制御フロー
Rust では match は値を直接返す式です。C 言語系の switch 文とは異なり、Rust の match 式は厳密に網羅的であり、起こり得るすべての値やバリアントが明示的に処理されていることをコンパイラが保証します。マッチガード (if condition) や包含範囲 (..=)、分配束縛と組み合わせることで堅牢な分岐制御が可能です。
構文
let status = match code {
200 | 201 => "SUCCESS",
400..=499 => "CLIENT_ERROR",
_ => "OTHER",
};
パラメータと値
この構文の主な構成要素と指定可能な値:
| パラメータ | 型 | 説明 |
|---|---|---|
| match expr | Expression | 複数のパターンに対して値を評価し、一致したアームの結果を返します。 |
| _ | Wildcard Discard | 残りのあらゆる値に一致し、コンパイラの網羅性チェックを満たします。 |
| Match Guard | Condition | match アームに追加する補助的な if 条件(例:n if n > 100 => ...)。 |
そのまま実行できるコード例
Compilra で実行可能Rust をローカルにインストールせずに、この動作する完全なコード例を直接実行できます:
fn main() {
let test_status_codes = [200, 304, 404, 503, 999];
println!("=== Rust Exhaustive Pattern Matching Engine ===");
for &code in &test_status_codes {
// 1. Expression-driven exhaustive match returning &str
let category = match code {
200 | 201 | 204 => "Fast-Path Success (2xx)",
301 | 302 | 304 => "Cache / Redirect (3xx)",
400..=499 => "Client Parameter Fault (4xx)",
500..=599 => "Server Upstream Failure (5xx)",
_ => "Unclassified Protocol Code", // Exhaustive catch-all
};
// 2. Pattern matching with conditional match guard
let action = match code {
c if c == 200 => "Forward payload directly to consumer",
c if c >= 500 => "Trigger incident response alert to SRE team",
_ => "Log standard diagnostic audit event",
};
println!("Status Code [{}]: {:<30} | Action: {}", code, category, action);
}
}期待される出力:
=== Rust Exhaustive Pattern Matching Engine === Status Code [200]: Fast-Path Success (2xx) | Action: Forward payload directly to consumer Status Code [304]: Cache / Redirect (3xx) | Action: Log standard diagnostic audit event Status Code [404]: Client Parameter Fault (4xx) | Action: Log standard diagnostic audit event Status Code [503]: Server Upstream Failure (5xx) | Action: Trigger incident response alert to SRE team Status Code [999]: Unclassified Protocol Code | Action: Log standard diagnostic audit event
動作のしくみ: ステップ解説
- 8-15 行目: 複数のリテラル (|)、包含範囲 (400..=499)、ワイルドカード (_) に対して code を評価します。
- 18-22 行目: 独自のブール条件のためのマッチガード (c if c >= 500) を示します。
- 24 行目: 式から返された束縛値より、評価済みカテゴリとアクションを直接出力します。
重要ポイント
- すべての match アームは同じ戻り値型へ評価される必要があり、型安全性が保たれます。
- Rust コンパイラは網羅性を検証するため、_ ワイルドカードなしで取り得るケースを漏らすとコンパイルエラーになります。
- 400..=499 のような包含範囲は 400 以上 499 以下のすべての整数に一致します。
- パイプ演算子 (|) を使うと単一アーム内に複数のパターンを連結できます。
よくある間違い: match 式での非網羅的パターンエラー
取り得るすべての整数値をカバーしていない場合や _ フォールバックパターンを省略した場合、コンパイルできません。
❌ 誤り
let res = match x { 1 => "One", 2 => "Two" }; // Compile Error: pattern `_` not covered✅ 正しい例
let res = match x { 1 => "One", 2 => "Two", _ => "Other" }; // Correct: exhaustive関連するRustチュートリアルとコンパイラ
Rust の match パターンマッチング:網羅性と表現力
網羅的な match 式とマッチガードを使って Rust のパターンマッチングを習得します。
Rust のゼロコストシーケンスイテレータと For ループ
借用イテレーション (&vec)、イテレータアダプタ (filter, count)、値を返す無限 loop 式など Rust のゼロコストイテレータを習得します。
Rust の関数と暗黙のブロック式戻り値最適化
Rust の式指向関数(セミコロンを省く暗黙の末尾リターン、明示的な return キーワード、ブロック式)を習得します。
Rust オンラインコンパイラ
Compilra IDE で開く