Sub topic 8
Branching with match
match compares a value against a list of patterns and runs the code for the first pattern that fits. It is Rust's main tool for multi-way branching. It is also an expression, so it produces a value, and the compiler checks that you have handled every possible input.
This chapter assumes you know if/else expressions, let and let mut, the primitive types, and basic enum syntax. You should also be able to build and run a program with cargo.
The shape of a match
A match has a scrutinee (the value being inspected) and a list of arms. Each arm is pattern => expression, separated by commas.
fn describe(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
x if x % 2 == 0 => "positive even",
_ => "positive odd",
}
}
fn main() {
println!("{}", describe(7));
}This prints positive odd. Four things happen here:
- The arms are tried from top to bottom, and the first match wins.
i32::MIN..=-1is a range pattern. Both ends are inclusive.x if x % 2 == 0binds the value toxand adds a guard, an extra boolean condition._is the wildcard. It matches anything and binds nothing.
Because match is an expression, the whole thing is the function's return value. There is no semicolon after the closing brace.
Exhaustiveness
The compiler requires every possible value of the scrutinee to be covered by some arm. This is called exhaustiveness checking. It is the main reason match is safer than a chain of if/else if: forgetting a case is a compile error, not a runtime surprise.
Two details trip people up:
- A guard does not count toward coverage. The compiler does not try to reason about arbitrary boolean expressions. In
describeabove, the armx if x % 2 == 0covers nothing as far as the checker is concerned, so the final_is required. - Ranges are checked precisely. You can cover a whole integer type without a wildcard by writing the ranges out.
fn life_stage(age: u8) -> String {
match age {
0 => "newborn".to_string(),
n @ 1..=12 => format!("child, {n} years old"),
13..=19 => "teenager".to_string(),
20..=64 => "adult".to_string(),
65..=u8::MAX => "senior".to_string(),
}
}
fn main() {
println!("{}", life_stage(0));
println!("{}", life_stage(9));
println!("{}", life_stage(70));
}There is no _ arm, and it compiles, because 0, 1..=12, 13..=19, 20..=64, and 65..=255 together cover every u8. The pattern n @ 1..=12 is a binding. It tests that the value is in the range and also names it n so the arm can use it.
If you later change 20..=64 to 20..=63, the compiler reports that 64_u8 is not covered. This is the check working as intended.
Matching enums and destructuring
match is most useful with enums, because you can pull the data out of each variant as you match it.
enum Shape {
Circle(f64),
Rect { w: f64, h: f64 },
Point,
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Rect { w, h } => w * h,
Shape::Point => 0.0,
}
}
fn main() {
let shapes = [Shape::Circle(1.0), Shape::Rect { w: 2.0, h: 3.0 }, Shape::Point];
for s in &shapes {
println!("{:.2}", area(s));
}
}Each arm uses a different pattern syntax: a tuple variant Circle(r), a struct variant Rect { w, h }, and a unit variant Point. If you add a fourth variant to Shape, every match on it without a wildcard stops compiling until you handle it. This is the main reason to avoid a lazy _ arm on your own enums. The wildcard silences exactly the error that would have told you what to update.
Matching on borrowed data
The scrutinee here is &Shape, not Shape. Since Rust 2018, "match ergonomics" lets you write patterns without & against a reference. The bindings r, w, and h then become references (&f64). That is why the arithmetic still works: f64 implements multiplication with &f64.
The same idea matters when a pattern would move data out of the scrutinee. Matching Some(s) against an Option<String> by value moves the string into s, and the original is partly moved. To keep using the original, match on a reference.
fn main() {
let name: Option<String> = Some("Ada".to_string());
match &name {
Some(s) => println!("length {}", s.len()),
None => println!("no name"),
}
println!("{:?}", name);
}Here s is a &String, and name is still usable afterward. If you wrote match name instead, the last line would fail with a "borrow of partially moved value" error.
Combining patterns
You can build larger patterns from smaller ones. These forms can be mixed freely.
| Pattern | Example | Meaning | Column | Column |
|---|---|---|---|---|
| Literal | `0` | Equals this constant | ||
| Range | `1..=9` | Within the inclusive range | ||
| Or | `1 \ | 2 \ | 3` | Any one of the alternatives |
| Tuple | `(0, _)` | First is 0, second is anything | ||
| Binding with `@` | `n @ 1..=12` | Test the subpattern, and name the whole value | ||
| Guard | `x if x > 5` | Pattern fits and the condition is true | ||
| Wildcard | `_` | Anything, not bound | ||
| Rest | `..` | Ignore the remaining fields or elements |
Matching on a tuple of values is a clean way to branch on two conditions at once.
fn fizzbuzz(n: u32) -> String {
match (n % 3, n % 5) {
(0, 0) => "FizzBuzz".to_string(),
(0, _) => "Fizz".to_string(),
(_, 0) => "Buzz".to_string(),
_ => n.to_string(),
}
}
fn main() {
for n in 1..=15 {
println!("{}", fizzbuzz(n));
}
}The order matters here. (0, 0) must come before (0, _), or 15 would be reported as just Fizz.
Slices can be matched by shape too.
fn summarize(v: &[i32]) -> String {
match v {
[] => "empty".to_string(),
[x] => format!("one element: {x}"),
[first, .., last] => format!("from {first} to {last}"),
}
}
fn main() {
println!("{}", summarize(&[]));
println!("{}", summarize(&[4]));
println!("{}", summarize(&[1, 2, 3]));
}The three arms are exhaustive because every slice has length 0, length 1, or length 2 or more.
Every arm has the same type
Since match is an expression, all arms must produce the same type. An arm that never returns normally, such as return, break, continue, or panic!, has the never type !, which fits anywhere. This lets you bail out of one case while the others produce values.
fn parse_digit(c: char) -> u32 {
match c {
'0'..='9' => c as u32 - '0' as u32,
_ => panic!("not a digit: {c}"),
}
}
fn main() {
println!("{}", parse_digit('7'));
}The first arm yields a u32. The second yields !, which the compiler coerces to u32.
Common errors
- Non-exhaustive patterns (E0004). The message lists the uncovered values, such as
i32::MIN..=-1_i32orShape::Point. Add the arm, or add a wildcard only if you really want a default. - Mismatched arm types (E0308). One arm returns
&strand anotherString, or one ends with a semicolon and yields(). Check for stray semicolons after arm expressions. - Unreachable pattern warning. An early catch-all, or a repeated range, hides later arms. The compiler warns because those arms can never run.
- Moving out of a borrow. Matching
&Option<String>with a pattern that tries to take ownership gives a "cannot move out" error. Bind by reference instead. - Treating a guard as coverage. Arms with guards need a later arm that handles the case where the guard is false.
- Binding names that look like constants. In a pattern, a lowercase identifier always creates a new binding. It does not compare against an existing variable of that name. To compare against a value, use a guard such as
x if x == limit, or aconst.
Choosing match
Use match when you have three or more distinct cases, when you need to destructure data, or when you want the compiler to prove all cases are handled. For a single case of interest, if let is shorter. A plain if/else is fine for one boolean condition. The next chapter covers if let, while let, and let-else.
Exercise
In the describe function from the start of this chapter, you delete the final _ => "positive odd" arm. Does the code still compile? Why or why not?
Show answer
No. It fails with a non-exhaustive patterns error (E0004). The guarded arm x if x % 2 == 0 is not counted toward coverage, so the compiler sees that positive values (1..=i32::MAX) are not fully handled. Even though the guard would catch the even numbers, the odd numbers have no arm.
Exercise
Write a function sign_and_parity(n: i32) -> &'static str that returns "zero" for 0, "negative" for any negative number, "positive even" for positive even numbers, and "positive odd" otherwise, using a single match on the tuple (n.signum(), n % 2). What should the first arm look like?
Show answer
One working version is:
fn signandparity(n: i32) -> &'static str {
match (n.signum(), n % 2) {
(0, ) => "zero",
(-1, ) => "negative",
(1, 0) => "positive even",
=> "positive odd",
}
}
The first arm is `(0, ), because signum returns 0 only for zero and the remainder does not matter. The final _ is needed because the compiler cannot prove that signum` only returns -1, 0, or 1.