Sub topic 1
Patterns and match: the starting point
if let, while let, let else, and let chains are all built on patterns, and match is the construct where patterns are easiest to see. This chapter sets up the working model that the rest of the tutorial relies on. It covers what a pattern is, how match checks patterns, which pattern forms you will meet most often, and which mistakes cause most compiler errors.
Prerequisites
This chapter assumes you already know:
- Basic Rust syntax: functions,
letbindings, andprintln!. - The
OptionandResultenums and their variants (Some,None,Ok,Err). - That
matchexists and has arms. You do not need to be fluent with it. - Ownership and borrowing basics: what a move is, and what
&Tmeans.
You need any recent stable Rust toolchain for the examples here. Later chapters note the newer version requirements, such as those for let chains.
What a pattern is
A pattern describes the shape of a value. Rust checks a value against the pattern. If the shape fits, the pattern can also give names to parts of the value. These names are called bindings.
Patterns are not limited to match. They appear in many places:
| Place | Example | Notes |
|---|---|---|
| `match` arm | `Some(n) => ...` | Any pattern is allowed. All cases must be covered. |
| `let` statement | `let (a, b) = pair;` | The pattern must always succeed. |
| Function parameter | `fn f(&(x, y): &(i32, i32))` | The pattern must always succeed. |
| `for` loop | `for (i, v) in list.iter().enumerate()` | The pattern must always succeed. |
| `if let` / `while let` | `if let Some(n) = opt` | The pattern may fail. Covered in later chapters. |
The last column matters. Some places accept only patterns that always match, and some accept patterns that may fail. The next chapter names these two groups irrefutable and refutable. For now, remember that match is the construct that handles both kinds, because it tries several patterns in order.
How match works
A match expression takes a value, called the scrutinee, and compares it with each arm's pattern from top to bottom. The first arm that fits runs, and its expression becomes the value of the whole match.
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Point,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rect { w, h } => w * h,
Shape::Point => 0.0,
}
}
fn main() {
println!("{:.2}", area(&Shape::Circle(1.0)));
println!("{:.2}", area(&Shape::Rect { w: 2.0, h: 3.5 }));
println!("{:.2}", area(&Shape::Point));
}Three rules explain most of what you see in this program:
- Arms are tried in order. The first matching arm wins, so put specific patterns before general ones.
matchis an expression. Every arm must produce the same type, heref64. An arm that returns, panics, or loops forever has type!and fits anywhere.matchmust be exhaustive. The compiler checks that every possible value is covered by some arm. If you delete theShape::Pointarm, compilation fails with error E0004 (non-exhaustive patterns) and the message lists the missing case.
Exhaustiveness is the main reason to use match. When you add a variant to an enum, the compiler points to every match that needs updating. The shorter constructs in this tutorial give up that check in exchange for brevity, and that trade-off recurs in the chapter on choosing a construct.
In this example, shape is a reference, &Shape. Rust's default binding modes (often called match ergonomics) make r, w, and h references into the value (&f64). That is why w * h works: &f64 * &f64 is implemented and returns f64.
Pattern forms you will use
Here is a compact tour of the forms that appear in match arms and carry over unchanged into if let and the other constructs.
fn classify(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
1 | 2 | 3 => "small",
x if x % 2 == 0 => "even and large",
_ => "odd and large",
}
}
fn main() {
for n in [-5, 0, 2, 10, 11] {
println!("{n}: {}", classify(n));
}
let pair = (3, -3);
match pair {
(x, y) if x + y == 0 => println!("opposites"),
(x, _) if x % 2 == 1 => println!("x is odd"),
_ => println!("other"),
}
let age = 15;
match age {
n @ 13..=19 => println!("teen, {n}"),
n => println!("age {n}"),
}
}- Literals and ranges:
0matches exactly zero.i32::MIN..=-1matches an inclusive range. - Alternatives:
1 | 2 | 3matches any of the listed patterns. - Wildcard:
_matches anything and binds nothing. Use it for values you do not need. - Bindings: a plain name such as
nmatches anything and binds the value to that name. - Destructuring:
(x, y),Shape::Rect { w, h }, andSome(n)take a value apart. Use..to skip the remaining fields, as inShape::Rect { w, .. }. - Guards:
if conditionafter a pattern adds a boolean test. The arm runs only if the pattern matches and the guard is true. @bindings:n @ 13..=19tests a sub-pattern and also keeps the whole matched value under the namen.
A guard is a plain boolean test, not part of the pattern. The compiler ignores guards when it checks exhaustiveness. A match made only of guarded arms is rejected unless a final unguarded arm covers the rest. The _ arm in classify is the one that makes it exhaustive.
Guards are also the first hint of the problem that let chains solve later. A guard can add a boolean test to a pattern, but it cannot add a second pattern match.
A diagram of the evaluation
The "no arms left" case never happens at run time. The compiler rules it out when it checks exhaustiveness.
Bindings, borrowing, and moves
A binding in a pattern either copies, moves, or borrows part of the scrutinee. Which one happens depends on the scrutinee's type and on whether you match the value or a reference to it.
fn main() {
let name: Option<String> = Some(String::from("Ada"));
match &name {
Some(n) => println!("hello, {n}"),
None => println!("no name"),
}
// `name` is still usable because we matched on a reference.
println!("{:?}", name);
}If you write match name { Some(n) => ... } instead, the String moves into n. The later println!("{:?}", name) then fails with E0382 (borrow of partially moved value). Integers and other Copy types are copied, so they never cause this problem.
Keep this in mind for the whole tutorial. if let Some(n) = name moves in exactly the same way, and the fix is the same: match on &name, or call a method such as name.as_ref(). The chapter on bindings, shadowing, and moves returns to this topic.
Common errors
Non-exhaustive patterns (E0004). You forgot a variant or a range of numbers. Add the arm, or add _ => ... if a default is correct. Be careful with _ on enums you own. It silences the compiler when you add a variant later, which removes the main benefit of match.
Mismatched arm types (E0308). One arm returns () and another returns a value. This often happens when you add a semicolon inside an arm block by accident. Check that every arm ends with an expression of the same type.
A lowercase name that binds instead of comparing. In a pattern, a bare identifier is always a new binding unless it names a constant, a unit struct, or an enum variant in scope.
const LIMIT: u32 = 10;
fn check(value: u32) -> &'static str {
let limit = 10;
match value {
LIMIT => "at the constant limit",
_ => match value {
// `limit` is a new variable here. It matches everything.
limit => "bound to a fresh name",
},
}
}
fn main() {
println!("{}", check(10));
println!("{}", check(3));
}The uppercase LIMIT compares the value with the constant. The lowercase limit in the pattern does not refer to the local variable of the same name. It creates a new binding that matches any value. The compiler warns about the unused variable, and a later arm after such a binding would be reported as unreachable. If a warning says a pattern is unreachable, look for a binding that is swallowing every case.
Moving out of a borrow (E0507). Matching *reference or a field behind a reference with a binding that would need ownership fails. Match on the reference itself and use the borrowed bindings, or clone what you need.
Unreachable pattern warnings. An earlier arm already covers every value that a later arm would match. Reorder the arms so the specific one comes first.
When match is more than you need
Consider a program that only cares about one variant:
fn main() {
let config_port: Option<u16> = Some(8080);
match config_port {
Some(port) => println!("listening on {port}"),
_ => {}
}
}This is correct, but the _ => {} arm is only there to satisfy the exhaustiveness rule. It adds two lines, an extra level of indentation, and no information. Rust has shorter constructs for this situation. The next chapters introduce them one at a time:
if letruns code when one pattern matches.while letrepeats code while a pattern keeps matching.let elseunwraps a value or leaves the current scope.- Let chains combine several pattern matches and boolean tests in one condition.
Each construct uses the same pattern syntax you saw above. The differences are in what happens when the pattern does not match, and that is why the distinction between patterns that always match and patterns that may fail comes next.
Exercise
What does the compiler do when a match has no arm for the value None of an Option, and why does that matter when you later add a variant to an enum?
Show answer
It rejects the program with error E0004 (non-exhaustive patterns), because match must cover every possible value. The same check means that adding a variant to an enum makes the compiler flag every match that does not handle it yet, so you cannot forget a case. A catch-all _ arm hides this check.
Exercise
In match value { limit => "x", _ => "y" }, where limit is a local variable holding 10, which arm runs when value is 3, and what warning do you expect?
Show answer
The first arm runs. A lowercase identifier in a pattern creates a new binding that matches any value, so it does not compare against the local variable. The compiler warns that the _ arm is unreachable, and may also warn about an unused variable.
Exercise
Given let name: Option<String> = Some(String::from("Ada"));, why does match name { Some(n) => println!("{n}"), None => {} } followed by println!("{:?}", name) fail to compile, and how do you fix it?
Show answer
Matching name by value moves the String into n, so name is partially moved and cannot be used afterwards (E0382). Fix it by matching on a reference with match &name { ... }, or by using name.as_ref().