Sub topic 14
Diverging functions and the never type
This chapter assumes you can write functions with typed return values, use if/else and match as expressions, and use loop, break, continue, and return. It covers !, the never type, which describes expressions that never produce a value. It explains why panic!() can sit in a branch that must return an i32.
What "diverging" means
An expression diverges if control never continues past it to the next step. Some expressions diverge by transferring control elsewhere. Others diverge because the program stops or loops forever. The compiler gives these expressions the type !, read "never".
These expressions have type !:
return valuebreakandcontinuepanic!(...),unreachable!(),todo!(), andunimplemented!()std::process::exit(code)- a
loopwith nobreak - a call to any function declared with
-> !
None of them evaluate to a value, because execution never gets that far. The type system records this fact.
Declaring a diverging function
A function whose return type is ! is a diverging function. It must never return normally.
fn fail(msg: &str) -> ! {
panic!("{msg}");
}
fn checked_div(a: i32, b: i32) -> i32 {
if b == 0 {
fail("division by zero");
}
a / b
}
fn main() {
println!("{}", checked_div(10, 2));
}The if block without an else must have type (). The call fail(...) has type !, and the semicolon turns it into a statement. The compiler also knows that code after the call is only reached when b != 0.
The compiler checks the promise that a -> ! function never returns. If you add println!("done"); as the last statement of a -> ! function that can fall off its end, you get a "mismatched types" error. The compiler found a path that returns (), and () is not !.
Two bodies satisfy the check:
- A body that ends in a diverging expression, such as
panic!()orstd::process::exit(1). - A body that ends in a
loopwith nobreak.
use std::process;
fn exit_with(code: i32) -> ! {
println!("exiting with status {code}");
process::exit(code)
}
fn run_forever() -> ! {
let mut tick = 0u32;
loop {
tick += 1;
if tick == 3 {
exit_with(0);
}
}
}
fn main() {
run_forever();
}exit_with ends with process::exit(code) and no semicolon. That final expression has type !, which matches the declared return type. In run_forever, the loop has no break, so the loop never produces a value and the function body has type !. The only way out is the exit_with(0) call, which ends the whole process.
Coercion: why `!` fits anywhere
The key rule is that ! coerces to every other type. An expression of type ! can be used where the compiler expects i32, String, &str, or any other type. This works because no value of type ! ever exists at runtime. The "wrong" type can never be observed.
This is why all of these compile:
fn pick(flag: bool) -> i32 {
let x: i32 = if flag { 5 } else { panic!("flag was false") };
x
}
fn main() {
println!("{}", pick(true));
}An if/else needs both branches to have the same type. The first branch is i32. The second is !, which coerces to i32, so the whole expression is i32.
The same rule explains a very common pattern. A match arm that skips a loop iteration still fits into a match whose other arms produce numbers:
fn main() {
let inputs = ["4", "x", "10"];
let mut total = 0;
for s in inputs {
let n: i32 = match s.parse() {
Ok(n) => n,
Err(_) => continue,
};
total += n;
}
println!("{total}");
}The Ok arm has type i32. The Err arm is continue, which has type ! and coerces to i32. The program prints 14. return and break work the same way inside match arms.
Where diverging expressions show up
The following table lists the common forms and when to use each.
| Expression | Typical use |
|---|---|
| `panic!("msg")` | An unrecoverable error, or a violated invariant. |
| `unreachable!()` | A branch you can prove is never taken. It panics if you were wrong. |
| `todo!()` | A placeholder for code you have not written yet. |
| `unimplemented!()` | A deliberately missing feature. |
| `std::process::exit(n)` | End the program at once with a status code. Destructors do not run. |
| `return`, `break`, `continue` | Leave the current function or loop. |
| `loop {}` without `break` | A server loop or event loop that never ends. |
todo!() is useful during development. A function body of just todo!() compiles with any return type, so you can sketch signatures first and fill in bodies later:
fn parse_config(path: &str) -> Vec<String> {
todo!("read and parse {path}")
}
fn main() {
println!("signature checks out");
}This compiles and runs. parse_config is never called, so the todo! never fires.
The `main` function and `!`
A program's main normally returns () or a Result. A main declared fn main() -> ! is not accepted on stable Rust, because ! does not implement the Termination trait that main's return type needs. Write fn main() { run_forever(); } instead, as above. The diverging call is a statement, and main still returns () in the type checker's eyes.
The never type outside return position
Using ! as a return type is stable. Using it as a general type, for example in let x: ! = ... or Vec<!>, is limited on stable Rust. Check your toolchain's release notes before relying on it.
The stable stand-in for "an error that cannot happen" is std::convert::Infallible. It is an enum with no variants, so no value of it can be constructed. Result<T, Infallible> is a result that is always Ok. The compiler still wants an exhaustive match, and you satisfy it by matching the empty enum with no arms:
use std::convert::Infallible;
fn always_ok(n: i32) -> Result<i32, Infallible> {
Ok(n * 2)
}
fn main() {
let value = match always_ok(21) {
Ok(v) => v,
Err(never) => match never {},
};
println!("{value}");
}match never {} has zero arms, which is exhaustive because the type has no values. The expression has type !, so it coerces to i32 and fits the Err arm. Newer compilers can omit the Err arm entirely, but this form works on older toolchains too.
Common errors and gotchas
- Falling off the end. A
-> !function that can reach its closing brace fails with a mismatched-types error. Every path must panic, exit, loop forever, or call another diverging function. - Accidental
breakinloop. Aloopmeant to run forever that contains abreakhas type()or the break's value, not!. Your-> !function then stops compiling. exitskips cleanup.process::exitends the process without running destructors for values still in scope. Buffered writers may lose data. Prefer returning frommainwhen you can.panic!is not error handling. A panic unwinds or aborts the thread. Libraries should returnResultfor failures a caller can reasonably handle. Keep panics for bugs and broken invariants.- Expecting a type to flow outward. A diverging branch never decides the type of the whole expression. If every branch diverges, the whole expression is
!. Inlet x = if c { panic!() } else { return };, the type ofxis!, and the compiler warns about unreachable code after thelet. unreachable!()is a promise. If your reasoning is wrong, the program panics at runtime. The compiler does not check it.
Choosing the right diverging tool
Pick the form that tells readers what you mean:
- Use
returnor?for errors the caller can handle. - Use
continueorbreakto leave a loop iteration or the loop. - Use
panic!orunreachable!for bugs and impossible states. - Use
todo!while a function body is unfinished. - Use
process::exitin top-level command-line code when you need a specific exit status. Write a small-> !helper likeexit_withso callers can use it in any expression position.
Exercise
The function below is meant to read a number from a string slice, and it must stop the program with a message if parsing fails. Why does the Err arm compile even though it does not produce an i32, and what is the type of fatal("bad number")?
fn fatal(msg: &str) -> ! {
eprintln!("{msg}");
std::process::exit(2)
}
fn read(s: &str) -> i32 {
match s.parse::<i32>() {
Ok(n) => n,
Err(_) => fatal("bad number"),
}
}
Show answer
fatal("bad number") has type !, because fatal is declared with -> !. The type ! coerces to any type, so in this match it coerces to i32, and both arms agree. This is sound because the Err arm never produces a value: fatal ends the process with std::process::exit(2), so no non-i32 value is ever seen.
Exercise
A colleague writes fn serve() -> ! { loop { if done() { break; } } }. The compiler rejects it. Explain why, and give two ways to fix it.
Show answer
A loop containing break can finish, so its type is (), not !. The function body would then return (), which conflicts with the declared !. Fix it by removing the break so the loop truly never ends. Or replace the break with a diverging call such as std::process::exit(0). You can also change the return type to () if the function is meant to return.