Rust Match
match compares a value against a list of patterns and runs the code for the first pattern that fits. Think of it as a sorting machine: the value goes in at the top and drops into exactly one slot. It is one of Rust's most loved features, and you will use it everywhere — especially with enums, Option and Result later in the course.
A first match
fn main() {
let day = 3;
match day {
1 => println!("Monday"),
2 => println!("Tuesday"),
3 => println!("Wednesday"),
4 => println!("Thursday"),
5 => println!("Friday"),
_ => println!("Weekend"),
}
}Wednesday
Each line inside the braces is an arm: a pattern, the => arrow, and the code to run. Arms are separated by commas. The underscore _ is a wildcard that matches anything, and here it catches every number not listed above.
Matches must be exhaustive
The compiler insists that every possible value is handled. If you remove the _ arm from the example above, the program no longer compiles, because day could be 6, -1 or 1000:
error[E0004]: non-exhaustive patterns: `i32::MIN..=0_i32` and `6_i32..=i32::MAX` not coveredThis check is a safety net: you can never "forget" a case by accident. When you add a new possibility later (for example a new enum variant), the compiler shows you every match that needs updating.
Multiple values and ranges
One arm can match several values with | (read: "or"), or a whole range with ..=:
fn main() {
let month = 7;
let season = match month {
12 | 1 | 2 => "winter",
3..=5 => "spring",
6..=8 => "summer",
9..=11 => "autumn",
_ => "not a valid month",
};
println!("Month {} is in {}.", month, season);
}Month 7 is in summer.
Notice that match is an expression, just like if: it produces a value, which we store in season. All arms must then return the same type (&str here).
Pattern syntax at a glance
| Pattern | Matches |
|---|---|
5 |
exactly the value 5 |
'a' | 'e' |
either 'a' or 'e' |
1..=9 |
any value from 1 to 9, inclusive |
'a'..='z' |
any lowercase ASCII letter |
_ |
anything (ignored) |
n |
anything, and binds it to the name n |
n if n < 0 |
anything for which the guard n < 0 is true |
Blocks in arms
When an arm needs more than one line, wrap its code in curly braces:
fn main() {
let command = "save";
match command {
"open" => println!("Opening file..."),
"save" => {
println!("Saving file...");
println!("Saved 3 pages.");
}
"quit" => println!("Goodbye!"),
other => println!("Unknown command: {}", other),
}
}Saving file...
Saved 3 pages.
The last arm uses a name (other) instead of _. It also matches anything, but gives you access to the value so you can use it in the arm.
Match guards
A guard is an extra if condition after a pattern. The arm is chosen only when both the pattern matches and the guard is true:
fn describe(n: i32) -> &'static str {
match n {
0 => "zero",
x if x < 0 => "negative",
x if x % 2 == 0 => "positive and even",
_ => "positive and odd",
}
}
fn main() {
for n in [0, -4, 10, 7] {
println!("{} is {}", n, describe(n));
}
}0 is zero
-4 is negative
10 is positive and even
7 is positive and odd
Matching on tuples
You can match several values at once by putting them in a tuple. This is a neat way to replace nested if statements:
fn main() {
let light = "green";
let pedestrian = true;
let action = match (light, pedestrian) {
("red", _) => "stop",
("green", true) => "wait for the pedestrian",
("green", false) => "drive",
(_, _) => "slow down",
};
println!("Action: {}", action);
}Action: wait for the pedestrian
Tip: Arms are checked from top to bottom, so put specific patterns before general ones. A
_arm placed first would swallow every value, and the compiler warns that the arms below it are unreachable.
match vs. if
Use if when… |
Use match when… |
|---|---|
| you test unrelated conditions | you compare one value against many possibilities |
| there are only one or two cases | there are many cases or ranges |
| conditions are complex boolean logic | you want the compiler to check all cases are covered |
Test yourself
What does the _ pattern match?
- Only zero
- Nothing
- Any value
- Only negative numbers
Why might a match without a _ arm fail to compile?
- Matches need at least five arms
- Not every possible value is covered
_is required syntax at the end- Matches only work on strings
Which pattern matches the numbers 1, 2, 3, 4 and 5?
- 1..5
- 1..=5
- 1-5
- 1 to 5