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
matchtries 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. matchis an expression, so it can give a value tolet. 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 namePatterns 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.
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.
What does the match in the rule give when on_loan is 3?
Why does a match on a u32 with only arms 0 and 1..=3 fail to compile?
After let (title, days) = ("Night Garden", 14);, what is days?
A match has arms _ => "any" then 0 => "zero". What does it give for 0?
Remember
matchtries arms top to bottom, the first fit wins, and all cases must be covered.- Narrow cases first, broad ones after,
_last. Useif letfor a single pattern. - Patterns destructure tuples and structs into named pieces.
