← Back to Rust Course | Chapter 3: Control Flow | Lesson 5 of 7

Pattern Matching with match

match lets your program compare a value against several possible options and run different code for each one.

Basic match

match compares a value against a list of patterns in order and executes the code for the first pattern that matches. It is Rust's primary tool for branching on more than two possibilities.

Example: Basic match

markup
fn main() {
    let day = 3;
    match day {
        1 => println!("Monday"),
        2 => println!("Tuesday"),
        3 => println!("Wednesday"),
        _ => println!("Some other day"),
    }
}

Exhaustiveness

The Rust compiler requires every match to cover all possible values of the matched type. The _ wildcard pattern is a catch-all that satisfies this requirement for any values not explicitly listed.

Example: Exhaustiveness

markup
fn main() {
    let letter_grade = 'B';
    match letter_grade {
        'A' => println!("Excellent"),
        'B' => println!("Good"),
        'C' => println!("Average"),
        _ => println!("Needs improvement"),
    }
}

Matching Multiple Values

The | operator inside a pattern lets a single match arm handle several distinct values at once, avoiding repeated arms with identical code.

Example: Matching Multiple Values

markup
fn main() {
    let n = 4;
    match n {
        1 | 3 | 5 | 7 => println!("{} is odd (from list)", n),
        2 | 4 | 6 | 8 => println!("{} is even (from list)", n),
        _ => println!("Out of range"),
    }
}

match as an Expression

Like if, match is an expression and can produce a value directly, which is commonly assigned to a variable instead of duplicating logic across arms.

Example: match as an Expression

markup
fn main() {
    let number = 6;
    let description = match number % 2 {
        0 => "even",
        _ => "odd",
    };
    println!("{} is {}", number, description);
}
Common Mistakes
  1. Forgetting that match in Rust must be exhaustive -- every possible value of the type must be covered, or it won't compile.
  2. Using _ too early in a match, accidentally catching cases that should have been handled by a more specific arm listed after it.
  3. Trying to fall through between match arms like a C switch statement -- Rust's match arms never fall through.
Chapter Summary
  • match compares a value against a series of patterns and runs the code for the first one that matches.
  • Matches must be exhaustive; the _ wildcard pattern catches any remaining cases.
  • Multiple values can share one arm using the | pattern, e.g. 1 | 2 => ....
  • match is an expression, so it can produce a value just like if.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.