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

match

Rust は match キーワードによってパターンマッチングを提供します。これは C の switch のように使用できます。最初にマッチしたアームが評価され、すべての可能な値が 網羅されている必要があります。

fn main() {
    let number = 13;
    // TODO ^ `number` にさまざまな値を試してみる

    println!("Tell me about {}", number);
    match number {
        // 単一の値にマッチ
        1 => println!("One!"),
        // 複数の値にマッチ
        2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
        // TODO ^ 素数の値のリストに 13 を追加してみる
        // 包含範囲にマッチ
        13..=19 => println!("A teen"),
        // 残りのケースを処理
        _ => println!("Ain't special"),
        // TODO ^ このキャッチオールアームをコメントアウトしてみる
    }

    let boolean = true;
    // match も式である
    let binary = match boolean {
        // match のアームは、すべての可能な値を網羅していなければならない
        false => 0,
        true => 1,
        // TODO ^ これらのアームのいずれかをコメントアウトしてみる
    };

    println!("{} -> {}", boolean, binary);
}