Sub topic 2
Refutable versus irrefutable patterns
This chapter assumes you can write basic Rust functions, use Option and Result, and read a match expression. It also assumes you know what a borrow is. The chapter explains the property that decides which pattern constructs you can use in a given place: whether a pattern can fail to match.
Two kinds of patterns
A pattern describes the shape of a value and can bind parts of it to names. Rust sorts every pattern into one of two groups.
- An irrefutable pattern matches every possible value of the type it is checked against. It cannot fail.
- A refutable pattern can fail to match for some values of the type.
The sorting depends on both the pattern and the type of the value. The compiler decides it statically, before the program runs.
Here are patterns that are irrefutable for most types:
- A plain name such as
x. It matches anything and binds it. - The wildcard
_. - A tuple pattern whose elements are all irrefutable, such as
(a, b). - A struct pattern whose fields are all irrefutable, such as
Point { x, y }. - A reference pattern around an irrefutable pattern, such as
&n.
Here are patterns that are normally refutable:
- A literal such as
5or"ok". - A variant of an enum that has more than one variant, such as
Some(x),None,Ok(v), orErr(e). - A range that does not cover the whole type, such as
1..=9against ani32. - Any compound pattern that contains one of the above.
(a, Some(b))is refutable becauseSome(b)can fail.
struct Point {
x: i32,
y: i32,
}
fn main() {
let (a, b) = (1, "two");
let Point { x, y } = Point { x: 3, y: 4 };
let &n = &10;
println!("{a} {b} {x} {y} {n}");
}Every let above uses an irrefutable pattern, so the program compiles and prints 1 two 3 4 10.
The same pattern can change category
Refutability is a property of the pattern together with the type. Compare the following two cases.
enum Meters {
Value(f64),
}
fn main() {
let Meters::Value(m) = Meters::Value(2.5);
println!("{m} meters");
}Meters has exactly one variant. The pattern Meters::Value(m) therefore matches every Meters value, and a plain let accepts it. The pattern Some(x) has the same syntactic shape, but Option has a second variant, None, so Some(x) is refutable.
Types with no possible values also affect the result. From Rust 1.82, a variant whose payload type is uninhabited can be omitted. For example, let Ok(v) = r; is accepted when r is a Result<i32, std::convert::Infallible>, because the Err case can never exist. This is a niche case, but it shows that the rule is about which values can exist.
Where each kind is allowed
Rust syntax has several places where a pattern appears. Some of them require an irrefutable pattern, because the program has no way to handle a failed match there.
| Position | Pattern required | What happens on a mismatch |
|---|---|---|
| `let` statement | Irrefutable | Not allowed. The compiler gives error E0005. |
| Function parameter | Irrefutable | Not allowed. The compiler gives error E0005. |
| Closure parameter | Irrefutable | Not allowed. The compiler gives error E0005. |
| `for` loop binding | Irrefutable | Not allowed. The compiler gives error E0005. |
| `match` arm | Either, but all arms together must be exhaustive | Next arm is tried. If no arm matches, you get error E0004. |
| `if let` | Refutable expected | The `if` block is skipped. |
| `while let` | Refutable expected | The loop ends. |
| `let else` | Refutable expected | The `else` block runs. |
The last three rows are the constructs this tutorial covers. They exist because let cannot take a refutable pattern. Each one supplies an answer to the question "what should happen if the pattern fails?"
The positions that need an irrefutable pattern all work with ordinary destructuring:
fn sum_pair(&(a, b): &(i32, i32)) -> i32 {
a + b
}
fn main() {
let pairs = vec![(1, 2), (3, 4)];
for (a, b) in &pairs {
println!("{a} and {b}");
}
let products: Vec<i32> = pairs.iter().map(|&(a, b)| a * b).collect();
println!("{products:?}");
println!("{}", sum_pair(&pairs[0]));
}The for binding, the closure parameter |&(a, b)|, and the function parameter &(a, b) are all irrefutable patterns. This program prints the two pairs, then [2, 12], then 3.
What the error looks like
Suppose you write a refutable pattern where only an irrefutable one is allowed:
fn main() {
let maybe: Option<i32> = Some(5);
let Some(n) = maybe;
println!("{n}");
}The compiler rejects this with error[E0005]: refutable pattern in local binding. It also names the missing case, for example None not covered. It notes that the matched type is Option<i32>. In a for loop the message says refutable pattern in for loop binding. In a function parameter it says refutable pattern in function argument.
The reason for the rule is simple. A let statement has no place to go when the pattern fails, and neither do the other three positions. A for loop, for instance, would have no defined behavior for an element that does not match.
You have three ways to fix the error. Each handles the missing None case in a different way.
fn first_or_zero(values: &[i32]) -> i32 {
match values.first() {
Some(n) => *n,
None => 0,
}
}
fn main() {
let maybe: Option<i32> = Some(5);
if let Some(n) = maybe {
println!("got {n}");
}
println!("{}", first_or_zero(&[]));
println!("{}", first_or_zero(&[7, 8]));
}- Use
matchwhen you want to handle every case explicitly, asfirst_or_zerodoes. - Use
if letwhen only one case needs code, asmaindoes formaybe. - Use
let elsewhen the other case should leave the current scope. A later chapter covers it.
The opposite mistake: an irrefutable pattern in `if let`
The refutable constructs expect a pattern that can fail. If you give one an irrefutable pattern, the compiler does not reject the program. It warns instead.
fn main() {
let pair = (1, 2);
if let (a, b) = pair {
println!("{a} {b}");
}
}This compiles and prints 1 2, with a warning from the irrefutable_let_patterns lint. The condition is always true, so the if let adds nothing. A plain let (a, b) = pair; says the same thing without the extra block.
The lint also fires for while let and let else with an irrefutable pattern. An irrefutable pattern in while let is worse than useless. The loop never ends on its own, because the pattern never fails.
The lint also has a subtler form. In a chain of else if let branches, a branch whose pattern always matches makes every later branch unreachable. The compiler warns about this too, and it is usually a sign that the code is not doing what you meant.
How the compiler decides
The compiler checks patterns by asking whether the set of patterns covers every possible value of the type. This is the same exhaustiveness check that match uses. A let statement is treated like a match with a single arm. The let is accepted only if that one arm already covers the whole type. This is why refutability is not a runtime concept. Nothing about the actual value, such as Some(5) being obviously Some, affects the result.
Nested patterns
One refutable part is enough to make the whole pattern refutable. This matters when you destructure a value that contains several layers.
(a, b)against(i32, i32)is irrefutable.(a, Some(b))against(i32, Option<i32>)is refutable, because the second element can beNone.Point { x: 0, y }is refutable, becausexcan be a number other than0.Point { x, y: _ }is irrefutable.
When you are unsure, read the pattern from the outside in and ask at each position whether a different value could appear there.
Checking your understanding
Refutability gives you a quick test for any pattern you are about to write. Ask whether it can fail. If it can, it needs one of the refutable constructs, and each of those construct has its own chapter in this tutorial. If it cannot, a plain let, a parameter, or a for binding is the simplest choice.
Exercise
Which of these patterns are refutable when matched against a value of type (i32, Option<i32>): (a, b), (a, Some(b)), (0, _), (_, _)? Which of them would a plain let accept?
Show answer
(a, Some(b)) and (0, _) are refutable. (a, Some(b)) fails when the second element is None, and (0, _) fails when the first element is not 0. (a, b) and (_, _) are irrefutable, so a plain let accepts only those two.
Exercise
The compiler reports error[E0005]: refutable pattern in local binding for let Ok(n) = "42".parse::<i32>();. Rewrite the code so it compiles and prints 42, using a construct that handles the error case. Then explain why the Ok(n) pattern would have been accepted by let if the error type were std::convert::Infallible.
Show answer
One fix is if let Ok(n) = "42".parse::<i32>() { println!("{n}"); }. A match with Ok(n) => println!("{n}") and Err(_) => {} also works. With Infallible as the error type, the Err variant cannot be built, because Infallible has no values. Ok(n) then covers every value that can exist, so it is irrefutable. This is accepted from Rust 1.82.