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

21.5 match Expressions

The match expression is Rust’s primary tool for complex pattern matching. It evaluates an expression and executes the code associated with the first matching pattern arm. A key feature of patterns within match arms (and other pattern contexts) is their ability to bind parts of the matched value to new variables. These bindings are then available within the scope of the corresponding arm’s code block.

match VALUE_EXPRESSION {
    PATTERN_1 => CODE_BLOCK_1, // Variables bound in PATTERN_1 are available here
    PATTERN_2 => CODE_BLOCK_2, // Variables bound in PATTERN_2 are available here
    // ...
    PATTERN_N => CODE_BLOCK_N, // Variables bound in PATTERN_N are available here
}

21.5.1 Example: Matching Option<T>

Handling optional values is a classic use case that demonstrates both pattern matching and variable binding:

fn check_option(opt: Option<&str>) {
    match opt {
        Some(message) => { // `Some(message)` is a pattern.
                          // If `opt` is `Some`, the inner value is bound to `message`.
            println!("Received message: {}", message); // `message` is used here.
        }
        None => { // `None` is a simple pattern matching the None variant.
            println!("No message received.");
        }
    }
}

fn main() {
    check_option(Some("Processing Data")); // Output: Received message: Processing Data
    check_option(None);                    // Output: No message received.
}

In this example, if opt contains a Some variant, the pattern Some(message) matches. The value inside the Some (which is a &str in this case) is bound to the variable message. This message variable is then accessible within the first arm’s code block. If opt is None, the second arm None => ... matches. The compiler ensures all possibilities (Some and None) are handled, guaranteeing exhaustiveness.