liveBook · Manning

Pattern matching

As explained in Learn Rust in a Month of Lunches

Pattern matching is the process of comparing a value against structural patterns and handling the matching case.

Pattern matching compares a value with structural patterns and runs the first matching arm. Rust requires every possible situation to be covered, so the compiler can catch missing cases. section 3.2.2 section 5.2.1

Build a match expression from these parts:

  • Write match followed by the value and a brace-delimited list of arms. section 3.2.2
  • Put a pattern on the left of => and the action or result on the right; separate arms with commas. section 3.2.2
  • Use _ as a wildcard for any remaining case. section 3.2.2
  • Remember that matching stops at the first matching arm, even when later arms would also match. section 3.2.2

Matching a number

A match can produce a value as well as perform an action: let my_number = 5; let second_number = match my_number { 0 => 0, 5 => 10, _ => 2, }; Every arm must produce a compatible type. Returning an integer from one arm and a string from another produces a compiler error. section 3.2.2

Matching structure and conditions

Patterns can describe tuples, bind values, and add conditions. For example, matching (sky, temperature) can distinguish ("cloudy", "warm"), while a match guard such as if children == 0 adds a condition to an arm. Option uses the same idea: Some(number) extracts a value, while None handles its absence. section 3.2.2 section 5.2.1

fn main() {
    let my_number: u8 = 5;
    match my_number {
        0 => println!("it's zero"),
        1 => println!("it's one"),
        2 => println!("it's two"),
    }
}

A minimal non-exhaustive match makes the compiler's coverage requirement concrete; adding a wildcard completes the cases. section 3.2.2

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains arm syntax, exhaustive coverage, wildcards, expressions, tuples, guards, ordering, and compatible result types.
Examples
Uses numbers, weather tuples, color tuples, marital status, and Some or None values as matching examples.
What it assumes
Assumes basic conditional control flow and types, while introducing tuples, enum variants, and generic Option patterns through examples.
What you can do after
Apply it via Rust match expressions to branch on values, extract nested data, return results, and handle missing cases.
How it connects
Connects pattern matching with match statements, tuples, match guards, wildcards, enums, Option, and exhaustive matching.

Also explained in

Compare how 12 books explain pattern matching →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.