Sub topic 7
Literal, range, wildcard, and or-patterns
This chapter assumes you can write a basic match over an enum and know that arms are tried in order. It covers the simplest pattern kinds: ones that test a value against fixed shapes. They work on integers, characters, tuples, and enum variants alike.
What a pattern is
A pattern describes the shape of a value. When a match runs, Rust tests the value against each arm's pattern from top to bottom and runs the first arm that fits. Patterns that can fail to match are called refutable. Patterns that always match, like a plain let x = 5;, are irrefutable. A match arm may use either kind, but the full set of arms must cover every possible value.
| Pattern kind | Example | Matches | Column | Column |
|---|---|---|---|---|
| Literal | `404`, `'q'`, `true`, `"yes"` | Exactly that value | ||
| Range | `1..=9`, `'a'..='z'` | Any value in the range | ||
| Wildcard | `_` | Anything, without binding it | ||
| Variable | `other` | Anything, bound to a name | ||
| Or-pattern | `500 \ | 502 \ | 503` | Any listed alternative |
| Rest | `..` | All remaining fields or elements |
Literal patterns and the catch-all
A literal pattern matches one exact value. Integers, characters, booleans, and string slices can all be literals. The compiler checks that the arms cover the whole type, and for an integer that usually needs a final catch-all arm.
fn describe(code: u16) -> &'static str {
match code {
200 => "ok",
404 => "not found",
400..=499 => "other client error",
500 | 502 | 503 => "server error",
_ => "unhandled",
}
}
fn main() {
for code in [200, 404, 418, 503, 301] {
println!("{code}: {}", describe(code));
}
}This prints ok, not found, other client error, server error, and unhandled for the five codes. Order matters here. 404 also falls inside 400..=499, so it must come first or the more specific arm never runs.
Two limits on literals are worth knowing. A &str value matches string literals directly, but a String does not, so call .as_str() first. Floating-point literals are allowed in patterns, but floats can never be proven exhaustive, so you always need a wildcard with them.
Range patterns
A range pattern matches any value inside an inclusive range written start..=end. Ranges work on integers and char.
fn kind(c: char) -> &'static str {
match c {
'a' | 'e' | 'i' | 'o' | 'u' => "vowel",
'a'..='z' => "consonant",
'A'..='Z' => "uppercase",
'0'..='9' => "digit",
_ => "other",
}
}
fn main() {
for c in ['e', 'x', 'Q', '7', '!'] {
println!("{c}: {}", kind(c));
}
}Several range forms exist:
a..=bis inclusive and has always worked.a..bis exclusive. It was stabilized in Rust 1.80, so older toolchains reject it.a..is open-ended, as in100.., and matches everything fromaupward.
Ranges can also give you exhaustiveness without a wildcard. If the ranges together cover every value of the type, the compiler accepts the match.
fn bucket(n: u8) -> &'static str {
match n {
0 => "zero",
1..=9 => "one digit",
10..=99 => "two digits",
100..=255 => "three digits",
}
}
fn main() {
for n in [0, 7, 42, 255] {
println!("{n}: {}", bucket(n));
}
}Change the last arm to 100..=254 and the compiler stops with an error saying 255_u8 is not covered. That precision is the reason to prefer ranges over a lazy _ when the domain is small and fixed. If the domain later grows, the compiler tells you.
Range endpoints must be literals or constants. A const works as a pattern too:
const MAX: u32 = 100;
fn grade(score: u32) -> char {
match score {
MAX => 'S',
90..=99 => 'A',
80..=89 => 'B',
0..=79 => 'C',
_ => '?',
}
}
fn main() {
println!("{}{}{}", grade(100), grade(85), grade(500));
}This prints SB?. Here MAX is compared against the value. It is not a new variable.
Wildcards, bindings, and the rest pattern
The wildcard _ matches any value and throws it away. That has a practical consequence for ownership. Because _ does not bind, it does not move the value.
fn main() {
let opt = Some(String::from("hi"));
match opt {
Some(_) => println!("has value"),
None => println!("empty"),
}
println!("{opt:?}");
}This compiles and prints Some("hi") after the match. Writing Some(_s) instead would bind _s and move the String out of opt, so the last line would no longer compile. A leading underscore only silences the unused-variable warning. It does not make the binding a wildcard.
When you want to use the leftover value, give the catch-all a name:
fn main() {
let n = 17;
let text = match n {
0 => "none".to_string(),
other => format!("got {other}"),
};
println!("{text}");
}The .. pattern skips all remaining fields in a tuple, struct, or tuple variant, or all remaining elements of a slice. You may use it once per pattern. Examples are (first, ..), (.., last), and Point { x, .. }.
Or-patterns
The | operator combines alternatives in one arm. It works at the top level of an arm, and it also works nested inside another pattern, as in Some(1 | 2 | 3). This nesting has been stable since Rust 1.53.
enum Command {
Walk(u32),
Run(u32),
Wait,
Quit,
}
fn describe(cmd: &Command) -> String {
match cmd {
Command::Walk(n) | Command::Run(n) => format!("travel {n} steps"),
Command::Wait => "wait".to_string(),
Command::Quit => "quit".to_string(),
}
}
fn small(opt: Option<u8>) -> bool {
match opt {
Some(1 | 2 | 3) => true,
_ => false,
}
}
fn locate(p: (i32, i32)) -> &'static str {
match p {
(0, 0) => "origin",
(0, _) | (_, 0) => "on an axis",
_ => "elsewhere",
}
}
fn main() {
println!("{}", describe(&Command::Run(3)));
println!("{}", describe(&Command::Walk(1)));
println!("{}", describe(&Command::Wait));
println!("{}", describe(&Command::Quit));
println!("{} {}", small(Some(2)), small(None));
println!("{}", locate((0, 5)));
}The first arm of describe binds n in both alternatives. Rust requires every alternative of an or-pattern to bind exactly the same names, with the same types and binding modes. This is why Command::Walk(n) | Command::Wait fails to compile: Wait has no n. Binding the same name from two different variants is a compact way to share one body.
Common errors
- Unreachable arm. A broad arm placed before a narrower one hides it. The compiler warns when an arm can never run, so treat that warning as a likely ordering bug.
- Non-exhaustive match. The compiler lists the uncovered values, such as
i32::MIN..=-1_i32or255_u8. Add the missing arm or a wildcard. - Matching a
Stringagainst a literal. Uses.as_str(), which gives a&str. - Catch-all too early.
_and bare names match everything, so they belong last. - Mismatched or-pattern bindings. Each alternative must bind the same set of names.
Choosing between a wildcard and explicit arms
A wildcard is the right choice when the leftover cases really share one behavior, such as "any other status code". When you match on your own enum, listing each variant explicitly is usually better than _. If you later add a variant, the compiler flags every match that needs to handle it. A wildcard silently absorbs the new variant, which can hide a bug.
Exercise
Write a function fn size(n: i32) -> &'static str using a single match with no wildcard arm. It must return "negative" for values below 0, "zero" for 0, "small" for 1 through 9, and "large" for 10 or more. Which range forms make the match exhaustive?
Show answer
Use i32::MIN..=-1 => "negative", 0 => "zero", 1..=9 => "small", and 10..=i32::MAX => "large". In Rust 1.55 or later, the last arm can also be written as the open-ended 10.. => "large". Together these cover every i32, so the compiler accepts the match without _.
Exercise
This code does not compile: match cmd { Command::Walk(n) | Command::Wait => ... }. Why does it fail, and how do you fix it?
Show answer
The alternatives bind different names. Walk(n) binds n, but Wait binds nothing, and every alternative of an or-pattern must bind the same names. Fix it by splitting the arms, or by using a pattern that does not bind, such as Command::Walk(_) | Command::Wait.