TExcelTAD
Home › Rust › Rust Match

Rust Match

match compares a value against a list of patterns and runs the code for the first pattern that fits. Think of it as a sorting machine: the value goes in at the top and drops into exactly one slot. It is one of Rust's most loved features, and you will use it everywhere — especially with enums, Option and Result later in the course.

A first match

rust · try it yourself
fn main() {
    let day = 3;

    match day {
        1 => println!("Monday"),
        2 => println!("Tuesday"),
        3 => println!("Wednesday"),
        4 => println!("Thursday"),
        5 => println!("Friday"),
        _ => println!("Weekend"),
    }
}
Wednesday

Each line inside the braces is an arm: a pattern, the => arrow, and the code to run. Arms are separated by commas. The underscore _ is a wildcard that matches anything, and here it catches every number not listed above.

Matches must be exhaustive

The compiler insists that every possible value is handled. If you remove the _ arm from the example above, the program no longer compiles, because day could be 6, -1 or 1000:

text
error[E0004]: non-exhaustive patterns: `i32::MIN..=0_i32` and `6_i32..=i32::MAX` not covered

This check is a safety net: you can never "forget" a case by accident. When you add a new possibility later (for example a new enum variant), the compiler shows you every match that needs updating.

Multiple values and ranges

One arm can match several values with | (read: "or"), or a whole range with ..=:

rust · try it yourself
fn main() {
    let month = 7;

    let season = match month {
        12 | 1 | 2 => "winter",
        3..=5 => "spring",
        6..=8 => "summer",
        9..=11 => "autumn",
        _ => "not a valid month",
    };

    println!("Month {} is in {}.", month, season);
}
Month 7 is in summer.

Notice that match is an expression, just like if: it produces a value, which we store in season. All arms must then return the same type (&str here).

Pattern syntax at a glance

Pattern Matches
5 exactly the value 5
'a' | 'e' either 'a' or 'e'
1..=9 any value from 1 to 9, inclusive
'a'..='z' any lowercase ASCII letter
_ anything (ignored)
n anything, and binds it to the name n
n if n < 0 anything for which the guard n < 0 is true

Blocks in arms

When an arm needs more than one line, wrap its code in curly braces:

rust · try it yourself
fn main() {
    let command = "save";

    match command {
        "open" => println!("Opening file..."),
        "save" => {
            println!("Saving file...");
            println!("Saved 3 pages.");
        }
        "quit" => println!("Goodbye!"),
        other => println!("Unknown command: {}", other),
    }
}
Saving file...
Saved 3 pages.

The last arm uses a name (other) instead of _. It also matches anything, but gives you access to the value so you can use it in the arm.

Match guards

A guard is an extra if condition after a pattern. The arm is chosen only when both the pattern matches and the guard is true:

rust · try it yourself
fn describe(n: i32) -> &'static str {
    match n {
        0 => "zero",
        x if x < 0 => "negative",
        x if x % 2 == 0 => "positive and even",
        _ => "positive and odd",
    }
}

fn main() {
    for n in [0, -4, 10, 7] {
        println!("{} is {}", n, describe(n));
    }
}
0 is zero
-4 is negative
10 is positive and even
7 is positive and odd

Matching on tuples

You can match several values at once by putting them in a tuple. This is a neat way to replace nested if statements:

rust · try it yourself
fn main() {
    let light = "green";
    let pedestrian = true;

    let action = match (light, pedestrian) {
        ("red", _) => "stop",
        ("green", true) => "wait for the pedestrian",
        ("green", false) => "drive",
        (_, _) => "slow down",
    };

    println!("Action: {}", action);
}
Action: wait for the pedestrian

Tip: Arms are checked from top to bottom, so put specific patterns before general ones. A _ arm placed first would swallow every value, and the compiler warns that the arms below it are unreachable.

match vs. if

Use if when… Use match when…
you test unrelated conditions you compare one value against many possibilities
there are only one or two cases there are many cases or ranges
conditions are complex boolean logic you want the compiler to check all cases are covered

Test yourself

What does the _ pattern match?

  1. Only zero
  2. Nothing
  3. Any value
  4. Only negative numbers

Why might a match without a _ arm fail to compile?

  1. Matches need at least five arms
  2. Not every possible value is covered
  3. _ is required syntax at the end
  4. Matches only work on strings

Which pattern matches the numbers 1, 2, 3, 4 and 5?

  1. 1..5
  2. 1..=5
  3. 1-5
  4. 1 to 5