21.5 Match Expressions

A match expression takes a value (or the result of an expression), compares it against multiple patterns, and executes the first matching arm. Each arm consists of a pattern, the => token, and the code to run or expression to evaluate:

match VALUE {
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
    PATTERN => EXPRESSION,
}

21.5.1 Simple Example: Option<i32>

fn main() {
    let x: Option<i32> = Some(5);
    let result = match x {
        None => None,
        Some(i) => Some(i + 1),
    };
    println!("{:?}", result); // Outputs: Some(6)
}

Because Option<i32> only has two variants (None and Some), the match is exhaustive. Rust forces you to either handle each variant or include a wildcard _.