Skip to content
Theory · Enums and match · lesson 4 of 8

match

You have already seen match take apart an item and an Option box. Now let's look at exactly how it chooses what to do.

Picture a sorting machine at the post office. Along the belt, from top to bottom, stand bins, and each bin says which sticker it accepts. An item rides past the bins and drops into the first one that fits it. The bin opens it right away and lays out the contents in labeled cells.

Questions come up at once. What if two bins fit? What if none fits? Let's look at a program that computes the delivery price:

Rust
enum Parcel {
    Letter,
    Package(u32),
}

fn price(p: Parcel) -> u32 {
    match p {
        Parcel::Letter => 50,
        Parcel::Package(kg) => kg * 100,
    }
}

fn main() {
    println!("{} {}", price(Parcel::Package(3)), price(Parcel::Letter)); // 300 50
}

Let's walk through the example line by line:

  1. match p takes the item and compares it with the lines inside the curly braces.
  2. For Parcel::Package(3) the first line does not fit, the second one does, and kg gets 3. The price is 3 * 100, that is, 300.
  3. For Parcel::Letter the first line fits, and the price is 50.
  4. The match is the function's last expression, so its value is the result of price.

Arms and patterns

Each line inside a match is an arm. Take the arm Parcel::Package(kg) => kg * 100, and break it into parts:

  • Parcel::Package(kg) is the pattern: a description of the values the arm accepts;
  • => is the arrow: "if the pattern fits, then";
  • kg * 100 is the expression the arm computes;
  • the comma separates the arm from the next one.

A pattern does two things at once. First it checks the variant: Parcel::Package(kg) does not fit a letter. If the variant matches, the pattern declares the variable kg and puts the variant's data into it. You do not write let, and kg is visible only inside its own arm.

The first arm that fits

match checks the arms from top to bottom and runs the first one whose pattern fits. It does not look at the remaining arms. Step through the program and watch which arm each item stops at and which variables appear in the main frame.

LiveHow match picks an armstep 1 of 11 · frames: 1

Three items with different stickers sit in one array.

Watch which arm runs and what the pattern puts into variables

The form Parcel::Tube { cm } is short for Parcel::Tube { cm: cm }, as in a struct literal: the field cm goes into a variable with the same name.

Here the machine picture falls short. A real bin only sorts, while a match arm also computes a value. That is why you can put a match on the right of let, like an if. All arms must give values of the same type: here each gives a u32.

Every variant is required

If an item fits no bin, the machine has nowhere to put it. Rust does not allow that situation: a match must cover every variant. The compiler does the check while building, before the program runs. This property is called exhaustiveness.

When you do not want to list every variant, you put the arm _ last. It fits any value and declares nothing. Instead of _ you can write a name, such as other: it also catches everything, but puts the value into a variable.

Rust
fn is_heavy(p: Parcel) -> bool {
    match p {
        Parcel::Package(kg) => kg > 10,
        _ => false,
    }
}

println!("{} {}", is_heavy(Parcel::Package(12)), is_heavy(Parcel::Letter)); // true false

The arm _ goes last: the arms below it can never run, and the compiler warns about that.

Interviewers like to ask this: "Why must a match be exhaustive?" The answer:

  • match checks the arms from top to bottom and runs the first one that fits;
  • every possible value needs an arm, or the build fails with error E0004;
  • when a variant is added to the enum, the compiler points at every match that does not handle it;
  • _ catches everything else, but then a new variant silently lands in that arm.

Common mistake

A variant was added to the enum, but its arm was forgotten:

Rust
enum Parcel {
    Letter,
    Package(u32),
    Tube { cm: u32 },
}

fn price(p: Parcel) -> u32 {
    match p { // ✗
        Parcel::Letter => 50,
        Parcel::Package(kg) => kg * 100,
    }
}
TEXT
error[E0004]: non-exhaustive patterns: `Parcel::Tube { .. }` not covered

The program does not compile, and the compiler names the forgotten variant. This is a build error, not a panic when a tube reaches the match. The fix is the arm Parcel::Tube { cm } => cm * 2.

Key points

  • An arm is a pattern, => and an expression; the pattern checks the variant and declares the variables for its data by itself.
  • match checks the arms from top to bottom and runs the first one that fits.
  • A match must cover every variant, or the build fails with E0004.
  • _ or a name in the last arm catches all the remaining values.