Sub topic 8
Why the else block must diverge
This chapter assumes you know Option and Result, basic match, and the difference between refutable and irrefutable patterns. You will see why the else block of a let else statement must never finish normally, which constructs satisfy that rule, and what the compiler says when you break it.
The rule
A let else statement has this shape:
let PATTERN = EXPRESSION else {
// this block must diverge
};If the pattern matches, its bindings are visible in the rest of the enclosing block. If it does not match, the else block runs. That block must have type ! (the never type), which means it cannot reach its closing brace. The compiler rejects any else block that might fall through.
Why the rule exists
Think about what happens after the let else statement. The next line uses the bindings, such as port. If the else block could finish normally, execution would continue to that line with port unbound. Rust has no uninitialized variables, so the language rules this out at compile time.
Compare if let, where bindings exist only inside the matching block. There the else branch can do anything, because nothing after it relies on the bindings. let else moves the bindings into the surrounding scope, so the failure path has to leave that scope.
flowchart TD
A[Evaluate expression] --> B{Pattern matches?}
B -- yes --> C[Bind names in the enclosing scope]
C --> D[Continue with the next statement]
B -- no --> E[Run else block]
E --> F[Must leave: return, break, continue, panic]Replace the fence above with the proper diagram form shown next.
What counts as diverging
An expression diverges when its type is !. The common ways to get there are:
| Expression | Where it is useful |
|---|---|
| `return` or `return value` | Inside any function or closure |
| `break` or `continue` | Inside a loop |
| `panic!`, `unreachable!`, `todo!` | When failure is a bug |
| `std::process::exit(code)` | When ending the program is correct |
| A call to a function that returns `!` | Custom helpers that always exit |
The ? operator is not on this list as a bare expression, because it only diverges on the error path. Use it before the let else, or write an explicit return Err(...).
Valid examples
Early return in a function:
fn parse_port(input: &str) -> Result<u16, String> {
let Ok(port) = input.trim().parse::<u16>() else {
return Err(format!("invalid port: {input}"));
};
Ok(port)
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("abc"));
}Skipping bad items in a loop with continue:
fn main() {
let inputs = ["10", "x", "30"];
let mut total = 0;
for text in inputs {
let Ok(n) = text.parse::<i32>() else {
println!("skipping {text}");
continue;
};
total += n;
}
println!("total = {total}");
}The else block can contain several statements. It only has to end in something that diverges, so you can log first and then leave.
What the compiler rejects
This version lets the else block fall through:
fn main() {
let value: Option<i32> = None;
let Some(n) = value else {
println!("no value");
};
println!("{n}");
}The compiler reports an error like `else clause of let...else does not diverge, with a hint that the block should end with return, break, continue, or panic!`. The fix is to add one of them:
fn main() {
let value: Option<i32> = None;
let Some(n) = value else {
println!("no value");
return;
};
println!("{n}");
}Related restrictions
- The expression on the right of
=cannot end with a closing brace}, such as a bareiformatch. Wrap it in parentheses or assign it to a variable first. This avoids ambiguity about whichelsebelongs to what. - The pattern should be refutable. An irrefutable pattern makes the
elseunreachable, and the compiler warns about it. let elsedoes not have anelse ifform. For more branches, usematch.
Exercise
This function does not compile. Explain why, and give two different fixes. fn first_even(items: &[i32]) -> i32 { let Some(&n) = items.iter().find(|x| *x % 2 == 0) else { println!("none found"); }; n }
Show answer
The else block ends after println!, so control would continue to n with n unbound. The block must diverge. Fix one: add return 0; after the println!. Fix two: replace the block body with panic!("none found"). Using std::process::exit(1) also works.