Patterns: ranges, guards, @
So far patterns have checked an enum's variant. But match can sort plain numbers too.
Imagine the sorting machine has learned to weigh. One bin now says "exactly 0 kg", another "from 3 to 10 kg". At a third bin stands an inspector who lets a package through only if his condition holds. And a fourth bin also sticks a label with the weight onto the package. Let's sort packages by weight:
fn main() {
let kg = 4;
let size = match kg {
0 => "empty",
1 | 2 => "tiny",
3..=10 => "light",
_ => "heavy",
};
println!("{size}"); // light
}Let's walk through the example line by line:
let size = match kg { … };puts thematchon the right oflet: the value of the arm that runs goes intosize.- The arm
0does not fit: the weight is not zero. - The arm
1 | 2does not fit: 4 is neither 1 nor 2. - The arm
3..=10fits, because 4 lies between 3 and 10.sizegets"light". println!("{size}")printslight.
Patterns for numbers
You cannot take a number apart into variants the way you do a Parcel, but you can compare it with a pattern. There are three kinds of such patterns.
Literal
0 => fits only the value 0. A literal can be any number, character or quoted string.
Several values with |
1 | 2 => fits 1 or 2. The bar reads as "or" and joins any number of patterns.
Range
3..=10 => fits any number from 3 to 10 inclusive. The form ..= includes both ends: both 3 and 10 land in this arm.
There are about four billion numbers of type i32, and you cannot list them all. So a match on a number almost always ends with an arm _: without it the compiler finds uncovered values and stops the build with error E0004.
Match guard
Sometimes a pattern is not enough, and you need a more complex check. After a pattern you can add if with a condition; this is a match guard:
let kg = 150;
let size = match kg {
0 => "empty",
n if n > 100 => "too heavy",
1..=10 => "light",
_ => "heavy",
};
println!("{size}"); // too heavy- The arm
0does not fit. - The pattern
nfits any number and puts 150 inton. The conditionn > 100is true, so the arm runs. - The arms
1..=10and_are never reached, and the program printstoo heavy.
An arm with a guard runs only when the pattern fits and the condition is true. If the condition is false, match moves on to the next arm, as if the pattern had not fit. For kg = 4 the second arm would be skipped, and the arm 1..=10 would run.
@: check and remember
A range checks a number but gives it no name. The form n @ 1..=10 does both: it checks that the value lies in the range and puts it into n. You need it when the value has no name of its own: match takes apart the result of a call or an expression, such as match kg * 2. In the example below kg does have a name, but the form is the same.
let kg = 7;
match kg {
n @ 1..=10 => println!("light, {n} kg"), // light, 7 kg
n => println!("{n} kg"),
}- The value 7 lies in the range
1..=10, so the first arm fits. @puts 7 inton, and the arm printslight, 7 kg.- The last arm
ncatches all other numbers, like_, but with a name.
Here the machine picture falls short. A real inspector can notice that no bin accepted a package. But the compiler does not look into a guard: when it checks exhaustiveness, it assumes an arm with if may not run.
Common mistake
All cases are handled with guards, and no _ is put at the end:
let diff: i32 = -3;
let sign = match diff { // ✗
d if d < 0 => "lighter",
d if d >= 0 => "heavier or equal",
};
println!("{sign}");error[E0004]: non-exhaustive patterns: `i32::MIN..=i32::MAX` not coveredThe program does not compile, even though the two conditions together cover every number. i32::MIN..=i32::MAX is every number of type i32, from the smallest to the largest: the compiler counts the whole range as uncovered. The compiler does not read the guards and assumes both arms may fail. The fix is a last arm without a guard: _ => "heavier or equal".
Key points
- A pattern for a number is a literal
0, several values1 | 2or a range3..=10, where..=includes both ends. - A guard
n if n > 100runs only if the pattern fits and the condition is true; otherwisematchmoves on. n @ 1..=10checks the range and puts the value inton.- A
matchon a number ends with an arm_: the compiler ignores guards when it checks exhaustiveness.