Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
Introduction to Rust  ›  Capstone Project

Pattern Matching and Destructuring

Pattern Matching & Destructuring 15 minmatch compares a value against patterns in order and must cover every possibility, and patterns can pull tuples and structs apart into named pieces.

Pattern Matching and Destructuring

The library's front desk sorts every request by its shape: a return, a new loan, a renewal. Rust's match does the same for values, and the compiler checks you have not forgotten a case. It is one of the features Rust programmers miss most in other languages.

The rule

match tries patterns top to bottom and must cover every case.

let on_loan: u32 = 2;
let label = match on_loan {
    0 => "all in",
    1..=3 => "a few out",
    _ => "busy",
};
  • Each arm is pattern => result. The first arm whose pattern fits wins; later arms are skipped.
  • A pattern can be a literal (0), a range (1..=3), alternatives (4 | 5), a name that captures the value, or _, which matches anything.
  • match is an expression, so it can give a value to let. Every arm must give the same type.
  • Exhaustive: if some possible value matches no arm, the program does not compile.

Destructuring pulls a value apart inside the pattern:

let loan = ("Night Garden", 14);          // (title, days)
let (title, days) = loan;                  // tuple split into two names

struct Book { title: String, pages: u32 }
let book = Book { title: String::from("Iron Tides"), pages: 380 };
let Book { title, pages } = book;          // struct split by field name

Patterns also add guards: n if n > 10 => "very busy" matches only when the condition holds.

if let handles a single pattern when you do not care about the rest:

if let 0 = on_loan {
    println!("every copy is on the shelf");
}

The shortcut

Write a match in three moves: list the special cases, order them narrow to broad, finish with a catch-all.

Labelling a loan by days heldStep 1 of 4
  1. Special cases

    0 days means "just borrowed"; 1 to 21 is "on time"; more is "overdue".

The trap is putting _ first. It matches everything, so later arms can never run, and the compiler warns that they are unreachable.

Drills

Answer fast — trust the rule.

quick drill

What does the match in the rule give when on_loan is 3?

quick drill

Why does a match on a u32 with only arms 0 and 1..=3 fail to compile?

quick drill

After let (title, days) = ("Night Garden", 14);, what is days?

quick drill

A match has arms _ => "any" then 0 => "zero". What does it give for 0?

Remember

  • match tries arms top to bottom, the first fit wins, and all cases must be covered.
  • Narrow cases first, broad ones after, _ last. Use if let for a single pattern.
  • Patterns destructure tuples and structs into named pieces.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainMake the match exhaustive

A shelf's loan count is a u32. Write a match that labels 0 as "all in", 1 to 3 as "a few out", and anything else as "busy", then explain why removing the last arm breaks the build and what if let is for.