Pattern Matching and Destructuring
match compares a value against patterns in order and must cover every possibility, and patterns can pull tuples and structs apart into named pieces.
Unpack structured values and make the set of possible match cases explicit.
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");
}