Sub topic 3
Branching with match
This chapter assumes you can define an enum with variants that carry data, and that you know the basics of references and borrowing. Here you will learn how match selects a branch, how it extracts data from a variant, and which rules its arms must follow.
How match works
A match expression compares one value against a list of patterns, called arms, from top to bottom. It runs the first arm whose pattern fits. Each arm has the form pattern => expression.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn cents(coin: &Coin) -> u32 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
println!("{}", cents(&Coin::Dime));
}This prints 10.
match is an expression
A match produces a value, so you can return it, as cents does, or assign it to a variable:
let label = match 3 {
1 => "one",
2 => "two",
_ => "many",
};Because the whole match has one value, every arm must produce the same type. An arm that returns &str next to an arm that returns i32 is a compile error. An arm that never returns, such as panic!() or return, is the exception, because it has the type ! and fits anywhere.
Remember the semicolon after the closing brace when the match sits in a let statement.
Binding data from variants
A pattern can name the data inside a variant. The names it introduces are available only in that arm.
enum Event {
KeyPress(char),
Click { x: i32, y: i32 },
Close,
}
fn describe(event: &Event) -> String {
match event {
Event::KeyPress(c) => format!("key {c}"),
Event::Click { x, y } => {
let side = if *x < 0 { "left" } else { "right" };
format!("click on the {side} at ({x}, {y})")
}
Event::Close => String::from("close"),
}
}
fn main() {
let events = [
Event::KeyPress('q'),
Event::Click { x: -4, y: 9 },
Event::Close,
];
for event in &events {
println!("{}", describe(event));
}
}Output:
key q
click on the left at (-4, 9)
closeThree details to notice:
- The tuple variant
KeyPress(c)binds by position. The struct-like variantClick { x, y }binds by field name. - An arm that needs several statements uses a block. The last expression in the block, without a semicolon, is the arm's value.
eventis a reference, soc,xandyare references too. That is why the code writes*x < 0. Chapter "Moves, references, and binding modes in patterns" covers this in detail.
Arm order and the wildcard
Arms are tested in order, so put specific patterns before general ones. The pattern _ matches anything and discards the value. A bare name such as other also matches anything, but it binds the value so you can use it.
An arm placed after a catch-all can never run, and the compiler warns about it.
Common errors
| Symptom | Cause |
|---|---|
| `match arms have incompatible types` | Arms return different types. Convert them to one type. |
| Missing comma between arms | An arm with a non-block expression needs a trailing comma. Block arms do not. |
| `non-exhaustive patterns` | Some value has no arm. The next chapter covers this check. |
| Unused value warning for `_` | Use `_` when you do not need the value, or a named binding when you do. |
Exercise
What is the type and value of x after let x = match 5 { 1..=3 => "low", _ => "high" };, and why must both arms have the same type?
Show answer
x is a &str with the value "high", because 5 is outside 1..=3 and falls through to the wildcard. A match is a single expression, so Rust needs one type for its result, and every arm must produce that type.