In a Rust line parser, what does `let Some((key, value)) = line.split_once('=') else { return None; };` do, and why must its `else` diverge?
answer
- refutable pattern in a let
- bindings for the rest of the block
- no value on the miss path
- never type, E0308
basics
~20 slet-else, stable since Rust 1.65, binds key and value for the rest of the block when the pattern matches; otherwise its else block runs. That block must diverge (return, break, continue, panic) because no value exists to bind, and a non-diverging else is E0308.
solid answer
~40 sA plain `let` needs an irrefutable pattern; `let Some((key, value)) = line.split_once('=');` alone is E0005, *refutable pattern in local binding*. `let`-`else`, stable since Rust 1.65, accepts a refutable pattern: on a match the bindings live until the end of the enclosing block, and on a miss the `else` block runs. Since there would be nothing to put in `key` and `value`, the `else` must diverge, meaning it has type `!`: `return`, `break`, `continue` or a panic. An `else` that evaluates to a value is E0308, `` `else` clause of `let...else` does not diverge ``. The result is a parser whose happy path stays unindented: each guard either binds the next piece or leaves the function.
code
rust · 26 linesstruct Entry<'a> {
key: &'a str,
port: u16,
}
fn parse_line(line: &str) -> Option<Entry<'_>> {
let Some((key, value)) = line.split_once('=') else {
return None; // the else block must diverge
};
let Ok(port) = value.trim().parse::<u16>() else {
eprintln!("bad port in {line:?}");
return None;
};
// `key` and `port` stay in scope for the rest of the function.
Some(Entry { key: key.trim(), port })
}
fn main() {
for line in ["http = 8080", "# comment", "admin = 99999"] {
if let Some(e) = parse_line(line) {
println!("{} -> {}", e.key, e.port);
} else {
println!("skipped {line:?}");
}
}
}go deeper
Recognise let PATTERN = expr else { return ... }; and say that the bindings stay usable after the statement.
Explain why the else must diverge, name E0308 for one that does not and E0005 for a refutable plain let, and compare it with if let.
Choose between let-else, ?, if let and match by what the miss path must do, and know the parenthesis rules for scrutinees ending in a brace or a && expression.
Use guard-style let-else as a readability convention for parsers and handlers, and agree with the team when early returns beat nested branching.
## The shape `let`-`else` is a `let` statement with a refutable pattern and a diverging fallback: ```plaintext let PATTERN = EXPRESSION else { DIVERGING_CODE }; ``` The Reference states both rules: *if an `else` block is present, the pattern may be refutable*, and *the `else` block must always diverge (evaluate to the never type)*. It was stabilised in **Rust 1.65**, together with breaking from labeled blocks, and needs no edition. When the pattern matches, its variables are bound for **the rest of the enclosing block**, exactly like an ordinary `let`. When it does not, the `else` block runs and must leave: `return`, `break`, `continue`, `panic!`, or a call to a function returning `!`. ## Why the `else` must diverge After a `let` statement, every variable it introduces must hold a value. On the miss path there is no `key` and no `value` to put anywhere, so the only sound option is for control to **not reach** the code after the statement. Rust expresses "never continues" with the never type `!`, and rustc checks that the `else` block has it: ```plaintext error[E0308]: `else` clause of `let...else` does not diverge ``` rustc adds *expected type `!`*, a help line suggesting *a diverging expression, such as `return` or `panic!(..)`*, and *...or use `match` instead of `let...else`* when you really wanted a fallback value. ## How it compares | Construct | Pattern | Bindings visible | Miss path | |---|---|---|---| | `let PAT = e;` | irrefutable only | rest of the block | none; a refutable pattern is E0005 | | `let PAT = e else { ... };` | refutable | rest of the block | must diverge | | `if let PAT = e { ... } else { ... }` | refutable | first block only | any code | | `match e { ... }` | all variants | per arm | per arm, exhaustive | | `e?` | `Option` or `Result` only | the unwrapped value | returns early with the `None`, or with the error converted by `From` | Choose `let`-`else` when the pattern is not just "the `Ok` of a `Result`", when you need to log or return something different on the miss, or when you destructure an enum variant: `let Command::Set { key, value } = cmd else { return Err(...) };`. The material on the `?` operator covers propagation. ## Syntax restrictions rustc enforces a few rules that catch people out: 1. **The scrutinee cannot end in `}`.** `let Some(x) = if flag { a } else { b } else { return; };` is rejected: *right curly brace `}` before `else` in a `let...else` statement not allowed*. Wrap the scrutinee in parentheses. 2. **A bare `&&` or `||` expression is not allowed as the scrutinee**: *a `&&` expression cannot be directly assigned in `let...else`*; parenthesise it. 3. **An irrefutable pattern makes the `else` dead code.** rustc warns *unreachable `else` clause* under `irrefutable_let_patterns`. 4. **The statement ends with a semicolon after the `else` block**, because it is still a `let` statement. ## Where it pays off - **Parsers and handlers**: each step either binds the next piece of input or returns early, so the main logic sits at one indentation level. - **Loop bodies**: `let Some((k, v)) = line.split_once('=') else { continue };` skips a malformed line and keeps the loop going. - **Replacing nested `if let` pyramids** whose `else` branches all bail out the same way. - **Logging before leaving**: the `else` block may run any statements first, as long as it ends by diverging. ## Reading the parser example The snippet below runs three lines through `parse_line`: 1. `"http = 8080"` passes both guards: `split_once('=')` returns `Some(("http ", " 8080"))`, and `" 8080"` trims and parses as a `u16`. 2. `"# comment"` has no `=`, so the first `else` returns `None` before any parsing. 3. `"admin = 99999"` passes the first guard, but `99999` does not fit a `u16`, so the second `else` logs the line and returns `None`. rustc itself points to it: the E0005 help for a refutable plain `let` suggests adding `else { todo!() }`.
- Inside a Rust `for` loop, can a let-else use `continue` instead of `return`?Yes. `continue` has the never type `!`, so it diverges: `let Some((k, v)) = line.split_once('=') else { continue };` skips the malformed line and moves to the next one. `break` works the same way to stop the loop.
- Why does `let Some(x) = if flag { a } else { b } else { return; };` fail to parse?rustc does not allow the scrutinee of a let-else to end in a right curly brace, because `} else {` would be ambiguous with an `if`'s own `else`. It reports *right curly brace `}` before `else` in a `let...else` statement not allowed*; wrap the `if` in parentheses.
- In Rust, when is `?` a better fit than let-else?When the value is an `Option` or `Result` and you want to hand the `None` or error straight to the caller, converted with `From`. let-else fits when the pattern is something else, such as an enum variant, or when the miss path must log, return a different value or `continue`.
let-else is a turnstile: you pass through holding your ticket (the bindings), or you are sent back the way you came; nobody stands past the turnstile without a ticket, which is why the else must leave.
- the else of a let-else can supply a default value for the binding
- bindings from let-else are visible only inside a following block
- a plain let with Some(x) compiles and panics at run time on None
- let-else requires the 2024 edition
- the else block may fall through as long as it logs the failure
Assumes Rust 1.99 on edition 2024; let-else has been stable since Rust 1.65 on every edition.