Why does rustc reject `let Config { host, tls: Some(cert), .. } = load_config();` with E0005, and where must a Rust pattern be irrefutable?
answer
- can this pattern ever fail?
- one nested Some decides it
- let, parameters, closures, for
- if let warns the other way
basics
~20 sThe nested Some(cert) cannot match a Config whose tls is None, so the whole pattern is refutable, and let accepts only patterns that always match. Function parameters, closure parameters and for loops have the same rule.
solid answer
~50 sA pattern is **irrefutable** if it matches every possible value of its type and **refutable** if some value can fail it. One refutable sub-pattern makes the whole pattern refutable, so `tls: Some(cert)` turns the `Config` pattern refutable, and rustc reports E0005, "refutable pattern in local binding", with "pattern `Config { tls: None, .. }` not covered". Plain `let`, function parameters, closure parameters and `for` loop bindings all demand irrefutable patterns, because there is no other branch to run. `if let`, `while let`, `let`-`else` and `match` arms take refutable ones, and an irrefutable pattern there draws the `irrefutable_let_patterns` warning. The fix is to keep the `let` irrefutable by binding `tls` as a whole and deciding what `None` means next, or to use the `let`-`else` that rustc's help suggests. Since Rust 1.82, a variant holding an empty type such as `Infallible` can be left out, so `let Ok(v) = ...` compiles for a `Result<u32, Infallible>`.
code
rust · 20 lines#[derive(Debug)]
struct Config { host: String, port: u16, tls: Option<String> }
fn load_config() -> Config {
Config { host: "db.internal".into(), port: 5432, tls: None }
}
fn connect() -> Result<String, String> {
// Keep the let irrefutable: bind the Option itself...
let Config { host, port, tls } = load_config();
// ...then decide what a missing certificate means.
let Some(cert) = tls else {
return Err(format!("{host}:{port} needs a TLS certificate"));
};
Ok(format!("{host}:{port} with {cert}"))
}
fn main() {
println!("{:?}", connect());
}go deeper
Recall the two words and the rule: let, parameters, closures and for loops need patterns that always match; if let and match handle the ones that can fail.
Explain why a single nested Some makes the whole pattern refutable, read the not covered value in E0005, and name the irrefutable_let_patterns warning for the opposite mistake.
Choose the repair by what None means: rebind the Option, use let-else, use match, or change the field type, and know the 1.82 rule that makes Result<T, Infallible> patterns irrefutable.
No lead decision lives here; at most, a review preference for keeping struct unpacking irrefutable and handling each optional field where its failure policy is visible.
## Refutable and irrefutable patterns Every pattern either **can** fail to match some value of its type or **cannot**: - An **irrefutable** pattern matches every value. `x`, `_`, `(a, b)` against a pair, `Config { host, .. }` and `&(x, y)` against a reference all qualify. - A **refutable** pattern can fail. `Some(x)` fails on `None`; `0..=9` fails on `10`; `[a, b]` against a slice fails on any length other than two. Refutability is **compositional**: a struct, tuple or reference pattern is irrefutable only if every sub-pattern inside it is. That is the whole story of the failing line. `Config { host, .. }` is irrefutable, but the field pattern `tls: Some(cert)` is not, so the complete pattern can fail for any `Config` whose `tls` is `None`. ## What rustc reports ```plaintext error[E0005]: refutable pattern in local binding --> src/main.rs:9:9 | 9 | let Config { host, tls: Some(cert), .. } = load_config(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ pattern `Config { tls: None, .. }` not covered | = note: `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant ``` rustc names the exact value the pattern misses, which is the fastest way to see *which* nested piece made it refutable. Its help line then suggests `let`-`else`. ## Where each kind is allowed | Position | Accepts | If the pattern is the other kind | |---|---|---| | `let` statement | irrefutable only | E0005, "refutable pattern in local binding" | | function parameter | irrefutable only | E0005, "refutable pattern in function argument" | | closure parameter | irrefutable only | E0005, "refutable pattern in closure argument" | | `for` loop binding | irrefutable only | E0005, "refutable pattern in `for` loop binding" | | `if let`, `while let` | both | irrefutable draws the `irrefutable_let_patterns` warning | | `let`-`else` | both | irrefutable draws "unreachable `else` clause" | | `match` arm | both | exhaustiveness is checked across all arms | The logic is the same everywhere: a plain `let` or a parameter has nowhere to go if the match fails, so the compiler insists it cannot fail; `if let` exists to handle failure, so an irrefutable pattern there is pointless rather than wrong, and the lint suggests replacing the `if let` with a `let`. The wording of E0005 also tells you *where* the pattern sits, which helps when the refutable pattern hides in a closure passed three calls deep: "local binding" means a `let`, "function argument" a parameter of a `fn`, "closure argument" a closure parameter, and "`for` loop binding" the pattern after `for`. In every case the error is reported at compile time; a plain `let` never fails at run time because a value did not fit its pattern. ## Fixing the line Decide what a missing certificate *means*, then pick the construct: 1. **Keep the destructuring irrefutable** and bind the `Option` itself: `let Config { host, port, tls } = load_config();`. Then handle `tls` on its own line, where the `None` case can return an error, fall back to plain TCP or panic with a message. This keeps the struct unpacking readable and puts the decision where a reviewer sees it. 2. **Use `let`-`else`**, as rustc's help suggests: the pattern stays refutable and the `else` block must diverge (`return`, `break`, `continue` or panic). How `let`-`else` and `if let` work as control flow is covered with loops and conditionals. 3. **Use `match`** when both outcomes carry real work. Changing the type is sometimes the honest fix: if `tls` can never be absent after loading, make the field `String` rather than `Option<String>`, and the original pattern becomes irrefutable. ## Patterns that are irrefutable even though they name a variant or a range - A **path to the only variant** of a single-variant enum: `let Reading::Celsius(t) = reading;` compiles. - A **range covering the whole type**: `let n @ 0..=255 = byte;` compiles for a `u8`. - An **array pattern** of irrefutable elements: `let [a, b] = [1, 2];` compiles, but `let [a, b] = v[..];` on a slice is E0005, because a slice's length is unknown. - **Empty-type variants (Rust 1.82)**: a variant whose payload can never exist may be omitted in common cases. With `fn parse() -> Result<u32, std::convert::Infallible>`, `let Ok(v) = parse();` is irrefutable on Rust 1.82 and later, because no `Err` value can be built. ## Interview points - Say "one refutable sub-pattern makes the whole pattern refutable". - Name the four irrefutable-only positions without hesitating. - Read rustc's "not covered" value as the diagnosis, then choose between rebinding, `let`-`else` and `match`.
- Why does `let [a, b] = [1, 2];` compile while `let [a, b] = v[..];` on a `Vec` fails?An array's length is part of its type, so a two-element array pattern of irrefutable elements always matches `[i32; 2]`. A slice's length is only known at run time, so `[a, b]` can fail, and rustc reports E0005 with "patterns `[]`, `[_]` and `[_, _, _, ..]` not covered". A slice pattern is irrefutable only with a lone rest pattern, as in `[..]` or `[all @ ..]`.
- With `fn parse() -> Result<u32, std::convert::Infallible>`, why does `let Ok(v) = parse();` compile on Rust 1.99?`Infallible` is an enum with no variants, so no `Err` value can ever exist. Since Rust 1.82, rustc lets a pattern omit variants whose payload is such an empty type in common cases, so `Ok(v)` counts as irrefutable here. Before 1.82 the same line was E0005.
- What does rustc say about `if let (a, b) = pair { .. }` when `pair` is a `(i32, i32)`?It compiles with the warning "irrefutable `if let` pattern" from the `irrefutable_let_patterns` lint, noting that the pattern will always match and suggesting a plain `let`. The `if let` adds a branch that can never be skipped.
- Only the top level of a pattern decides refutability; nested fields do not count.
- A `let` with a refutable pattern panics at run time when it fails to match.
- Function parameters may use `Some(x)`; callers just have to pass `Some`.
- `if let` with a pattern that always matches is a compile error.
- `let Ok(v) = parse();` can never compile, whatever the error type is.
Assumes Rust 1.99 on the 2024 edition; omitting a variant that holds an empty type, which makes let Ok(v) irrefutable for Result<T, Infallible>, has been stable since Rust 1.82.