Sub topic 8
Why the else block must diverge
This chapter assumes you know let else basics, Option and Result, and how match arms must all have a compatible type. It explains the one compile-time rule that shapes every let else: the else block must never finish normally. It also shows how to satisfy that rule and what the compiler error means.
The rule
A let else statement has this shape:
let PATTERN = EXPRESSION else {
// this block must diverge
};If the pattern matches, its bindings enter the surrounding scope and execution continues with the next statement. If the pattern does not match, the else block runs. That block must not complete. It has to leave the current flow with return, break, continue, a panic, a process exit, or an infinite loop.
If the block can finish normally, the compiler rejects the code with an error like this:
The message is a type error. The compiler requires the else block to have the type !, the "never" type. That type belongs to expressions that never produce a value because control never gets past them.
Why the compiler insists
Compare let else with a plain let. After this line, port is always initialized:
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("nope"));
}The statement after let else uses port without any check. That is only sound if every path that reaches it went through a successful match. The else block is the only other path, so it must not reach the next statement.
You can see the same logic by writing the code with match:
fn parse_port(input: &str) -> Result<u16, String> {
let port = match input.trim().parse::<u16>() {
Ok(port) => port,
Err(_) => return Err(format!("invalid port: {input}")),
};
Ok(port)
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("nope"));
}Here the Ok arm has type u16. The Err arm must also fit the type u16, and it does because return ... has type !, which coerces to any type. let else applies the same idea without the match boilerplate. It has no value to put in the failure case, so the only acceptable failure case is one that never produces a value.
What counts as diverging
Any expression of type ! works. The common ones are in this table.
| Expression | Effect | Typical use |
|---|---|---|
| `return value` | Leaves the function | Early exit with an error or default |
| `break` / `break 'label` | Leaves a loop | Stop processing when input runs out |
| `continue` | Skips to the next iteration | Ignore bad items in a loop |
| `panic!(...)`, `unreachable!()`, `todo!()` | Unwinds or aborts | Invariant violations, unfinished code |
| `std::process::exit(code)` | Ends the program | Command-line tools |
| `loop {}` with no `break` | Never ends | Rare. Embedded or server loops |
| A call to a function that returns `!` | Whatever the function does | Shared error-exit helpers |
Leaving a loop iteration
Inside a loop, continue is often the best choice. It skips bad items and keeps the loop body flat.
fn main() {
let lines = ["10", "x", "20", "stop", "30"];
let mut total = 0;
for line in lines {
if line == "stop" {
break;
}
let Ok(n) = line.parse::<i32>() else {
println!("skipping {line}");
continue;
};
total += n;
}
println!("total {total}");
}This prints skipping x and then total 30. The stop line ends the loop before 30 is read.
Your own diverging helper
You can write a function whose return type is !. Calling it as the last statement of the else block satisfies the rule, even though the call ends with a semicolon.
use std::process;
fn fail(message: &str) -> ! {
eprintln!("error: {message}");
process::exit(2);
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let Some(name) = args.get(1) else {
fail("missing name argument");
};
println!("hello, {name}");
}Run with no arguments, the program prints the error and exits with status 2. Run with one argument, it prints a greeting. The compiler accepts fail(...); because the call has type !, so the block cannot finish normally. A function that returns ! must itself never return, and the compiler checks that for the function body too.
Both paths must diverge
The check is about the type of the whole block, so every route through the block has to diverge. A conditional exit is not enough. Consider this else block:
else {
if verbose {
return;
}
}When verbose is false, the block ends normally and execution would continue with port unbound. The block has type (), so the compiler reports the same E0308 error. To fix it, make both branches diverge, or move the conditional work before the final divergence:
fn first_word(text: &str, verbose: bool) -> Option<&str> {
let Some(word) = text.split_whitespace().next() else {
if verbose {
println!("no words found");
}
return None;
};
Some(word)
}
fn main() {
println!("{:?}", first_word("hello world", false));
println!("{:?}", first_word(" ", true));
}The if can still do side work. What matters is that the last thing in the block is return None;.
The same reasoning applies to if and match inside the block. If every branch diverges, the whole expression has type ! and the block is accepted. One branch that falls through breaks the rule.
Loops need care
loop {} has type ! only when nothing can break out of it. A loop that contains a reachable break has a normal type, usually (). So else { loop {} } compiles, but else { loop { break; } } does not. Likewise, while and for loops never count as diverging, because the compiler assumes they can finish.
Related restrictions in the statement
The divergence rule is the main one, but a few other limits catch people.
- The pattern's names are not available in the
elseblock. If the pattern fails, nothing was bound. Withlet Ok(n) = text.parse::<i32>() else { ... }, you cannot read the error value in theelseblock. When you need it, usematch, or call.map_err(...)and?before thelet else. - The expression cannot end with a closing brace. Something like
let Some(x) = if a { b } else { c } else { return };is rejected, because the parser cannot tell whichelsebelongs to which construct. Put the expression in a separatelet, or wrap it in parentheses. - A top-level
&&or||is also rejected. Wrap the boolean expression in parentheses if you really need it. In practice this is rare, because a pattern match on a plain boolean is not useful. - The pattern must be refutable. If it can never fail, such as
let x = value else { return };, the compiler warns that theelseblock is unreachable. Use a plainletinstead.
Choosing a divergence
Pick the exit that matches the job the else block is doing:
- In a function that returns
OptionorResult, usereturn Noneorreturn Err(...). The caller decides what to do. - In a loop that processes many items, use
continuefor bad items andbreakwhen a bad item means the work is over. - In a command-line program's
main, call a helper such asfail, or return aResultfrommain. - For a state that should be impossible, use
unreachable!()orpanic!with a message that names the broken assumption.
Avoid panic! for ordinary bad input. A panic gives the caller no way to recover, and a returned error does.
Summary of the reasoning
A let else is a promise: after this line, the bindings exist. The else block is the only path that does not make the pattern match, so the compiler needs proof that this path never reaches the next line. That proof is the ! type. Everything in this chapter, including the error message, the loop gotcha, and the "both branches" rule, follows from that one requirement.
Exercise
This function fails to compile with "else clause of let...else does not diverge". Explain why, and give two different ways to fix it.
fn name_length(name: Option<&str>) -> usize {
let Some(name) = name else {
println!("no name given");
};
name.len()
}
Show answer
The else block ends with a println! statement, so it has type () and control would continue to name.len() with name unbound. The block must diverge. One fix is to add return 0; after the println!, so the function returns a default. Another fix is to replace the block body with panic!("no name given"); if a missing name is a bug. Returning Option<usize> and using return None; also works.
Exercise
The function containing each let else returns (). Which of these else blocks compile? (a) else { if debug { return; } } (b) else { loop {} } (c) else { loop { break; } } (d) else { std::process::exit(1) }
Show answer
Only (b) and (d) compile. In (b), the loop has no break, so it never ends and has type !. In (d), exit returns !. In (a), the block finishes normally when debug is false. In (c), the break lets the loop finish, so the block has type ().