In the if lesson, the delivery-fee rule was written as a chain of else if. Three rates are still easy to read. As the rates grow, the chain gets longer, and it is easy to leave a number out without noticing. With match, a rule like this is neater. match compares one value with a list of patterns: descriptions of the values you are looking for, such as the text "iced tea" or the numbers 0 to 4999. Then match runs the first branch whose pattern fits.
Look at the delivery-fee board at the cashier's desk of Rusdi's Pancake Stall. Every order total belongs to exactly one row: below $50 the fee is $10, from $50 to $99.99 it is $5, and from $100 up it is free. In this lesson's code, money is counted in cents, so $50 is written 5000. Rusdi won't use a board with gaps: if some total has no row, the board can't be used. In match code, the order total is the value being compared, and each row is one branch. The condition on the total in each row (such as "below $50") is the pattern, and the fee in that row is the result. The "no gaps" rule is called exhaustive: every possible value must have a branch.
match: one value, many branches
The function price below finds the price of a menu item with match:
fn price(menu: &str) -> u32 {
match menu {
"sweet pancake" => 3200,
"egg pancake" => 3800,
"iced tea" | "iced orange" => 500,
_ => 0,
}
}
fn main() {
println!("{}", price("egg pancake"));
println!("{}", price("iced orange"));
println!("{}", price("coffee"));
}
The output:
3800
500
0
- Each branch (arm) is written
pattern => result,. If the pattern fits, the value on the right of=>becomes the result of thematch. Arms are separated by commas. - Patterns are checked starting from the top arm. The first arm that fits is used, and the rest are skipped.
|means "or":"iced tea" | "iced orange"fits both texts._is the wildcard: a pattern that fits any value that no arm above it caught, likedefaultin a JavaScriptswitch."coffee"isn't on the menu, so it goes to_and the result is0.- The
matchhere is the function's last line and has no semicolon, so the functionpricehands over the result of thematch.
Ranges and several patterns
For numbers, a pattern can be a range with ..=, just as in for. This program picks the delivery fee from the order total:
fn main() {
let total: u32 = 3200 * 2 + 3800 * 1;
let delivery = match total {
0..=4_999 => 1000,
5_000..=9_999 => 500,
_ => 0,
};
println!("Total: {}, delivery: {}", total, delivery);
}
The output is Total: 10200, delivery: 0. This table shows which arm fits three totals:
total |
Arm that fits | delivery |
|---|---|---|
| 3200 | 0..=4_999 |
1000 |
| 7000 | 5_000..=9_999 |
500 |
| 10200 | _ |
0 |
0..=4_999fits 0 to 4999, including the end.4_999is the same as4999: an underscore inside a number is only there to make it easier to read, and is not the_wildcard.- Because
matchis an expression, its result goes straight intodelivery. The semicolon comes after the closing}, just likelet delivery = if ...;.
Every possibility must be covered
One day the cashier writes the fee board without its last row. In code, that means there is no _ arm:
let delivery = match total {
0..=4_999 => 1000,
5_000..=9_999 => 500,
};
With total at 7000, does the program print a fee of 500? Guess first, then look at the compiler's answer:
error[E0004]: non-exhaustive patterns: `10000_u32..=u32::MAX` not covered
--> src/main.rs:3:26
|
3 | let delivery = match total {
| ^^^^^ pattern `10000_u32..=u32::MAX` not covered
|
= note: the matched value is of type `u32`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
5 ~ 5_000..=9_999 => 500,
6 ~ 10000_u32..=u32::MAX => todo!(),
|
The compiler calculates by itself which numbers have no arm: 10000 up to the largest u32 (u32::MAX). Since the compile fails, nothing prints, not even for a total of 7000, which does have an arm. The program doesn't run at all. In the compiler's suggestion, todo!() is only a placeholder: replace it with the fee.
- The fix can be
_ => 0,or10_000.. => 0,(10000 and up). So what is required is that every value is caught, not that there must always be a_. - For
egg_stock: u8, the patterns0..=2and3..=255already cover all 256 values, so the code compiles without_. Aboolneeds onlytrueandfalse. - Text (
&str) can never be listed in full, so amatchon text always needs_. Without_, the compiler refuses withnon-exhaustive patterns: `&_` not covered, with the notea wildcard `_` is necessary.
match produces a value
Every arm of a match whose result is stored must have the same type, exactly as with if. Here the _ arm produces text, so the compiler refuses:
error[E0308]: `match` arms have incompatible types
--> src/main.rs:5:14
|
3 | let delivery = match total {
| ____________________-
4 | | 0..=9_999 => 1000,
| | ---- this is found to be of type `{integer}`
5 | | _ => "free",
| | ^^^^^^ expected integer, found `&str`
6 | | };
| |_____- `match` arms have incompatible types
The first arm is a number, so "free" is refused. Store 0, then write the word "free" when printing.
Guards and @ bindings
Sometimes a range isn't enough. A guard adds an if condition to an arm: the arm fits only when the condition is true. name @ pattern is a binding: the matching value is kept in a variable called name. The function below uses both:
fn check_order(portions: u32) {
match portions {
0 => println!("No orders yet"),
n @ 1..=5 => println!("{} portions, cooked straight away", n),
n if n > 20 => println!("{} portions? Call the buyer first", n),
n => println!("{} portions, into the queue", n),
}
}
fn main() {
check_order(0);
check_order(2);
check_order(8);
check_order(25);
}
The output:
No orders yet
2 portions, cooked straight away
8 portions, into the queue
25 portions? Call the buyer first
n @ 1..=5fits 1 to 5 and keeps the number inn.n if n > 20fits any value, as long as the conditionn > 20is true. 8 doesn't meet the condition, so it is checked against the next arm.- The pattern
nalone (no condition) catches everything left, like_, but also gives the value a name. - The compiler doesn't count guards when it checks whether a
matchis exhaustive, so you still need a last arm that catches everything.
🎯 A first look: match with Option
match is used most for a value that may or may not be there. For example prices.get(3), which asks for the item at position 3 of the array. An array of three prices has only positions 0 to 2, so .get(3) finds nothing:
fn main() {
let prices = [3200, 3800, 500];
match prices.get(3) {
Some(p) => println!("Price: {}", p),
None => println!("There is no menu item 3"),
}
}
The output is There is no menu item 3. Some(p) means there is a value (kept in p), None means there is nothing. The type that holds Some or None is called Option, and it is covered fully in the Result and Option lesson. You'll meet Option again in the Vec and HashMap lessons.
⚠️ Arms that leave gaps, get hidden, or don't match in type
- Forgetting
_. The compile fails with errorE0004 non-exhaustive patterns. Add_ => ...as the last arm. _at the top. The arms below it are never chosen, and the compiler warnsunreachable patternwith the noteno value can reach this. Put_at the bottom.- Matching a
String.Stringis also a type of text, and how it differs from&stris covered in the String lesson.match menuwithmenu: Stringand the pattern"iced tea"is refused:expected `String`, found `&str`. Writematch menu.as_str(), which readsmenuas a&str. - Arms of different types. Every arm whose result is used must produce the same type.
TL;DR: match value { pattern => result, ... } compares one value with the patterns (descriptions of the values you look for) of its arms (branches, pattern => result), starting from the top. The first arm that fits is used. A pattern can be a number, text, a range 0..=4_999 or several patterns with | (or). An arm can also have a guard n if n > 20 (an extra condition) or a binding n @ 1..=5 (keeps the matching value in n). _ fits every value that no arm above it caught. A match must be exhaustive: every possible value needs an arm. Otherwise the compile fails with E0004 non-exhaustive patterns. Text always needs _; numbers can be fully covered with ranges. match is an expression (code that produces a value), so all its arms must have the same type and its result can be stored: let delivery = match total { ... };.
⚡ One value, many branches
Write:
match menu {
"sweet pancake" => 3200,
"egg pancake" => 3800,
"iced tea" | "iced orange" => 500,
_ => 0,
}
Meaning: match compares menu (a menu item's name) with the patterns (the values it looks for) on the left of =>, starting from the top arm (branch). The first arm whose pattern fits hands over the value on its right: "egg pancake" gives 3800. | means "or". _ fits anything that no arm above it caught, like default in a JavaScript switch.
⚡ Ranges for numbers
Write:
let delivery = match total {
0..=4_999 => 1000,
5_000..=9_999 => 500,
_ => 0,
};
Meaning: total is the order total. The pattern 0..=4_999 is a range: 0 to 4999, including the end. match is an expression, code that produces a value, so its result goes straight into delivery, and all its arms must have the same type.
⚡ No gaps allowed
Guess first: the _ arm of the code above is removed, and total is 7000. Does the program still run, with delivery at 500?
No. The compile fails with E0004 non-exhaustive patterns, because totals of 10000 and up have no arm. The program doesn't run at all.
Meaning: A match must be exhaustive: every possible value needs an arm. Text can never be listed in full, so it always needs _. For numbers, ranges that cover every value are enough too.