Pattern matching
A pattern describes the shape of a value and can bind names to pieces of it. Patterns appear in match, if let, while let, let, and function parameters.
Detailed Explanation
A pattern is not a boolean test. It is a description of structure. Some(user) says "this is a Some, and call the inside user". Session { user_id, .. } says "this is a Session, bind user_id, ignore the rest". _ says "anything, and do not bind it". 0..=9 says "an integer in this range".
Patterns are either refutable or irrefutable. An irrefutable pattern always matches: let (a, b) = pair; is legal because a 2-tuple always has two slots. A refutable pattern might fail: let Some(x) = maybe; is a compile error, because maybe might be None. Refutable patterns belong in match, if let, and while let, which have a place for the failure. let-else is the exception that lets a refutable let exist if you provide a diverging else.
Bindings can be by move, by reference, or by mutable reference. Some(x) moves the inner value when it is not Copy. Some(ref x) binds x as &T. Some(ref mut x) binds &mut T. In modern Rust you more often write Some(x) and then use maybe.as_ref() on the scrutinee, or you match on &maybe so the default bindings are references. match &maybe { Some(x) => ... } gives x: &T.
You can match slices: [first, rest @ ..] binds the first element and the tail. You can match structs with .. to ignore remaining fields. You can match multiple patterns in one arm with |: 0 | 1. You can add a guard: n if n % 2 == 0. Guards are not patterns; they are extra booleans that run after the pattern matches.
Why this is a language feature and not a library: the compiler uses patterns to prove exhaustiveness and to move only the fields you named. A hand-rolled sequence of if and .unwrap() does neither. The cost is a syntax you have to learn, and a few rules about when a pattern is allowed.
When you reach for a pattern: anytime you open a compound value. Prefer let patterns for irrefutable destructuring at the top of a function. Prefer match when several shapes matter. Prefer if let when one shape matters.
Code Examples
struct Session {
user_id: u64,
token: String,
}
fn main() {
let session = Session { user_id: 17, token: "abc".into() };
let Session { user_id, .. } = session; // irrefutable: always a Session
println!("{user_id}"); // prints: 17
let maybe = Some(("ada", 3));
match maybe {
Some((name, n)) if n > 1 => println!("{name} x{n}"), // prints: ada x3
Some((name, _)) => println!("{name}"),
None => println!("nobody"),
}
}Common Gotchas
Refutable patterns cannot be used in plain `let`
`let Some(x) = maybe;` fails to compile. Use `if let`, `let-else`, or `match`.
Default bindings move
`match maybe { Some(x) => ... }` moves `x` out. Match on `&maybe` or use `.as_ref()` when you still need `maybe`.
`..` ignores remaining fields or elements
Without it, a struct pattern must name every field. Add `..` when you only care about some.
Guards run after the pattern binds
A failed guard still counts as a failed arm, and the next arm is tried. Exhaustiveness ignores guards.