Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 132 ยท Operators and Control Flow

match Expressions

Learn Rust match from scratch - arms, exhaustive checking, ranges, guards, @ bindings, tuples, enums with data, match as an expression and the compiler errors you will meet.

Almost every program has to choose between several possibilities: which command did the user type, which kind of shape is this, what did the network return? Many languages give you a switch statement for this. Rust gives you match, and it is a much stronger tool. A match compares a value against a list of patterns, runs the code of the first pattern that fits, and, this is the big difference, refuses to compile if you forgot a possibility.

In this lesson you will learn how match is built, why it must be exhaustive, how to match ranges, several values, tuples and enums, how guards add extra conditions, and how match hands back a value like any other expression. The if lesson came just before; the next lesson covers loops, and Patterns in Depth goes further with destructuring.

The shape of a match

A match has a value to inspect (the scrutinee) and a list of arms. Each arm is pattern => expression, and arms are separated by commas:

Rust Your first match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read it top to bottom. Rust tests the arms in order and runs the first one that matches. Here day is 3, so the third arm wins and the whole match evaluates to "Wednesday".

Three details are worth noticing:

  • 6 | 7 is an or-pattern: it matches if the value is 6 or 7.
  • _ is the wildcard. It matches anything and does not bind a name. It is the usual "everything else" arm.
  • The match is an expression. Its value is stored in name, so the statement ends with a semicolon after the closing brace, just like let x = 5;.

Because a match is an expression, every arm must produce the same type. If one arm returned a &str and another an integer, the compiler would stop you. The lesson on if expressions has the same rule for the branches of an if.

Exhaustiveness: the compiler has your back

Suppose you model the four compass directions with an enum, and then write a match that forgets one of them:

Rust A forgotten arm (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This does not compile. The key lines of the error are:

TEXT
error[E0004]: non-exhaustive patterns: `Direction::West` not covered
  --> main.rs:9:11
   |
 9 |     match d {
   |           ^ pattern `Direction::West` not covered

The compiler even tells you which value you forgot. Rust demands that a match be exhaustive: for every possible value of the scrutinee, at least one arm must match. This is not pedantry. In a language with a switch that silently falls through, a forgotten case is a bug that shows up in production. In Rust it is a compile error that shows up in your editor.

The fix is to add the missing arm:

Rust All four directions handled

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

There is a design lesson here. When you later add a fifth variant such as Up, every match over Direction that lists variants explicitly stops compiling, and the compiler walks you to each place you must update. That is the "exhaustive match as a refactoring safety net" idea, and it is a big reason Rust programs stay correct as they grow. We use it heavily in Modelling with Enums and Pattern Matching.

Be careful with a catch-all _ arm on your own enums. It silences the compiler exactly when you would want it to speak. If a match should be updated whenever a variant is added, list the variants and skip _.

Integers and strings need a catch-all

Enums have a small, known set of values, so you can list them all. An i32 has more than four billion values, so for integers (and for &str and most other types) you almost always need a final _ or a named catch-all:

Rust
let code = 404;
let text = match code {
    200 => "OK",
    404 => "Not Found",
    other => {
        println!("unusual code {other}");
        "Unknown"
    }
};

The name other also matches anything, but unlike _ it binds the value, so you can use it inside the arm. Use _ when you do not need the value and a name when you do.

Patterns you can use

Matching is not limited to single literals. These are the building blocks you will use every day.

Ranges, alternatives and guards

A range pattern matches every value inside it. Write 1..=9 for an inclusive range. (The exclusive form a..b is also allowed in patterns, since Rust 1.80.) An or-pattern | lists alternatives. A guard is an if condition after the pattern, and the arm only runs when the pattern matches and the guard is true:

Rust Ranges, alternatives, guards and @

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Look at the pieces:

  • i32::MIN..=-1 uses a constant as the start of a range. Constants and paths work in patterns.
  • 100.. is a half-open range: every value from 100 up. Together with the other arms, the ranges cover all of i32, so no _ is needed. The compiler really checks this and would reject the code if you changed 0 to 1.
  • x @ 4..=99 is an @ binding: it tests the range and also names the matched value x. Without it you would have a range but no variable.
  • The guard if x % 2 == 0 is checked only after the pattern matched. If it is false, Rust moves on to the next arm, which is the odd-number version.

Guards have one catch: the compiler cannot reason about them. A guard is just a boolean expression, so Rust does not count it when it checks exhaustiveness. If your last two arms were x if x < 0 and x if x >= 0 with no plain arm, the compiler would still complain that patterns are not covered. Put the unguarded arm last.

Order matters

Arms are tried from the top, so a broad pattern above a narrow one hides it. The compiler notices:

Rust An unreachable arm (warns)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

This compiles, but rustc prints warning: unreachable pattern, explaining that the 5 arm can never run because an earlier arm already matches everything. A warning like this nearly always means the arms are in the wrong order. Put specific patterns first and the general ones last.

Matching several values at once with a tuple

To decide based on two values together, match a tuple of them. This is the classic FizzBuzz without any nested if:

Rust Matching a tuple

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The tuple (n % 3, n % 5) is built on the spot and each arm describes the shape of both parts. (0, _) reads "first is zero, second is anything".

Matching enums that carry data

Rust's enums can hold data in their variants (you will study them fully in the Enums lesson). match is how you get that data out. The pattern names the variant, and the names inside it bind to the contents:

Rust Destructuring enum variants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Here the scrutinee is &Shape, a reference. Thanks to a feature called default binding modes, the names radius, width and so on become references to the fields (&f64), which is why the arithmetic works through automatic dereferencing and the shape is not moved out. If you matched an owned Shape and the variant held a String, the string would be moved into the binding, and the original value could not be used afterwards. When you only need to look, match on a reference.

Two familiar enums from the standard library work the same way. The next lesson group, starting with Option and Handling Absence, builds on this:

Rust
match maybe_number {
    Some(n) => println!("got {n}"),
    None => println!("nothing"),
}

match is an expression

Because every arm yields a value, you can use match anywhere an expression is allowed: in a let, as a function's last expression, or as an argument. Arms that do not produce a useful value can still be used for their side effects, as long as they all have type ():

Rust match as a function body and with strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

String literals are of type &str, so you can match a &str against them directly. A String is a different type, so you borrow it with .as_str() first (or &owned[..]). Forgetting this is one of the more common beginner errors: the error is E0308: mismatched types with the note "expected String, found &str", and rustc itself suggests the .as_str() fix shown above.

Blocks and early exits

An arm's right-hand side can be a block { ... } whose last expression is the value, or a statement-like expression that never returns, such as return, break, continue or panic!. These have the special "never" type, which fits any expected type:

Rust Arms that return, break or panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

In the second match, the 'x' arm is continue, which never produces a value, so Rust accepts it next to an arm that produces a u32. In the first function, the panic! arm is allowed for the same reason. Prefer returning a Result when bad input is a normal event; see Result and Recoverable Errors.

match versus if let

When you only care about one pattern and want to ignore the rest, a full match is noisy:

Rust
match config_value {
    Some(v) => println!("value: {v}"),
    _ => {}
}

The shorter form is if let, and the "otherwise" part is optional:

Rust
if let Some(v) = config_value {
    println!("value: {v}");
}

Use match when you must handle several cases or want the compiler to check you covered everything. Use if let or let ... else for the "one case matters" situations. Both are covered in Patterns in Depth, together with the handy matches! macro that turns a pattern into a bool.

Common mistakes

  • Using a variable name as a pattern. In match x { limit => ... } the name limit is a fresh binding that matches anything and shadows your variable, it does not compare against it. To compare against a value, use a const or a guard (n if n == limit).
  • Forgetting commas or braces. Arms with a block do not need a trailing comma, arms with a plain expression do.
  • Mixing arm types. All arms must have one common type. Use .to_string() or String::from consistently, or return &'static str from every arm.
  • A catch-all that hides variants. See the tip earlier: list variants explicitly when you want future-proofing.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does it mean that a match must be exhaustive?

    The compiler checks that no value can fall through without matching an arm. If one can, you get error E0004, naming a value you missed.
  2. 2. What is the value of this match?

    match 7 { 1..=5 => "low", 6 | 7 => "mid", _ => "high" }

    7 is not in 1..=5, but it matches the or-pattern 6 | 7, which is the second arm, so the result is "mid".
  3. 3. What does n @ 10..=20 do in a pattern?

    An @ binding tests a sub-pattern (here a range) and also gives the matched value a name you can use in the arm.
  4. 4. Why does match owned_string { "stop" => ... } fail when owned_string is a String?

    A string literal is a &str. A String is a different type, so borrow it as a &str with as_str() and then match.
  5. 5. Why does a match guard such as x if x < 0 not help the compiler prove exhaustiveness?

    The compiler treats a guarded arm as possibly not matching, so you still need an unguarded arm (often _) to cover the rest.

Summary

  • match value { pattern => expression, ... } runs the first arm whose pattern fits; it is an expression, so all arms share one type.
  • match must be exhaustive. Missing cases are compile error E0004 and the message names what you forgot.
  • Patterns include literals, ranges (1..=9, 100..), alternatives (a | b), the wildcard _, bindings, name @ pattern, tuples and enum variants with data.
  • A guard (pattern if condition) adds a runtime condition, but the compiler ignores guards when checking exhaustiveness.
  • Order matters: put specific arms before general ones; an unreachable arm triggers a warning.
  • Match on a reference (&shape) to look at data without moving it; use .as_str() to match a String.
  • Prefer listing enum variants over a catch-all _ so the compiler flags code you must update later.

Next: loop, while and for