Sub topic 1
Patterns and match: the starting point
Prerequisites
This chapter assumes you know basic Rust syntax (functions, let bindings, println!). It also assumes you know the Option and Result enums and the basics of ownership and borrowing. You do not need to know if let, let else, or let chains yet. The rest of the tutorial covers them.
What a pattern is
A pattern describes the shape of a value. Rust tests a value against a pattern. If the shape fits, the pattern can also bind parts of the value to names.
Patterns appear in many places:
matcharmsletstatements- function parameters
forloops
You have used patterns already. let (x, y) = (1, 2); uses a tuple pattern. for (i, item) in items.iter().enumerate() does too.
match as the baseline
match compares one value against a list of patterns, called arms. The compiler requires the arms to be exhaustive. That means every possible value must be covered by some arm.
fn main() {
let config_port: Option<u16> = Some(8080);
match config_port {
Some(port) => println!("listening on {port}"),
None => println!("using default port"),
}
}The first arm matches Some(port) and binds the inner value to port. The second arm matches None. If you delete one arm, the program fails to compile, because Option<u16> has two variants and both must be handled.
This exhaustiveness check is the main safety feature of match. When you add a variant to an enum later, the compiler points at every match that needs updating.
When match feels heavy
Often you care about only one case. Suppose you want to print a message only when the port is set:
fn main() {
let config_port: Option<u16> = Some(8080);
match config_port {
Some(port) => println!("listening on {port}"),
_ => {}
}
}The _ pattern matches anything and ignores it. The arm _ => {} exists only to satisfy exhaustiveness. It does nothing, yet it takes up space and makes the reader check that nothing is hiding there.
The same problem appears in let statements. This line does not compile:
fn main() {
let config_port: Option<u16> = Some(8080);
let Some(port) = config_port;
println!("{port}");
}The compiler rejects it because config_port could be None, and then the pattern would not fit. The error says the pattern is refutable, and a plain let accepts only patterns that cannot fail.
These two frictions lead to the constructs in this tutorial:
- A
matchwith one interesting arm and a do-nothing arm is awkward.if letis the shorter form. - A plain
letcannot use a pattern that might fail.let elselets it, as long as you say what happens on failure. - Repeating a
matchin a loop, or nesting several of them, gets noisy.while letand let chains address those cases.
How the pieces connect
Every one of these constructs is built on the same idea: test a value against a pattern, and bind names if it fits. They differ in what happens when the pattern does not fit. match forces you to cover that case. The others let you skip it, run an else branch, or leave the function.
Where patterns can go
| Place | Example | Pattern must be irrefutable? |
|---|---|---|
| `let` statement | `let (a, b) = pair;` | Yes |
| Function parameter | `fn show(&(x, y): &(i32, i32))` | Yes |
| `for` loop | `for (k, v) in map` | Yes |
| `match` arm | `Some(n) => ...` | No |
| `if let` / `while let` | `if let Some(n) = x` | No |
The last column previews the next chapter. An irrefutable pattern always fits. A refutable pattern can fail to fit. Where each kind is allowed decides which construct you need.
Exercise
The line let Some(x) = maybe_value; fails to compile when maybe_value is an Option<i32>. Why, and which two other constructs from this chapter's list could you use instead?
Show answer
Some(x) is a refutable pattern, because maybe_value might be None, and a plain let accepts only irrefutable patterns. You could use match with arms for Some and None, or if let Some(x) = maybe_value { ... } (and let else is a third option, covered later).