Sub topic 14
Diverging functions and the never type
This chapter assumes you can write Rust functions with typed parameters and return values, and that you know if/else and match are expressions. It covers functions that never return, and how the compiler uses that fact.
What a diverging function is
A diverging function never returns control to its caller. It might panic, exit the process, or loop forever. Its return type is !, called the never type.
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));
}This program prints 5. The call fail(...) ends with a semicolon, and the if block still type-checks as (). The compiler also knows that nothing after fail runs when b is zero.
Why `!` fits everywhere
An expression of type ! has no value, because it never finishes. The compiler therefore lets it stand in for any type. This is called coercion: ! converts to i32, String, (), or anything else.
This matters most in branches that must agree on a type. In the next example, one match arm produces a number and the other diverges.
fn parse_or_exit(s: &str) -> i32 {
match s.trim().parse::<i32>() {
Ok(n) => n,
Err(_) => {
eprintln!("not a number: {s}");
std::process::exit(1)
}
}
}
fn main() {
println!("{}", parse_or_exit(" 42 "));
}std::process::exit returns !. The Ok arm has type i32, the Err arm has type !, and the ! coerces to i32, so the match is an i32.
Expressions that already have type `!`
You have used several diverging expressions without naming the type.
| Expression | Why its type is `!` |
|---|---|
| `return value` | Leaves the function |
| `break` and `continue` | Jump out of the current iteration or loop |
| `panic!(...)` | Unwinds or aborts |
| `loop { }` with no `break` | Never ends |
| `unreachable!()`, `todo!()`, `unimplemented!()` | Panic with a message |
This is why the following line compiles. The continue arm needs no value.
fn main() {
let inputs = ["10", "x", "30"];
let mut total = 0;
for s in inputs {
let n: i32 = match s.parse() {
Ok(n) => n,
Err(_) => continue,
};
total += n;
}
println!("{total}");
}The output is 40. The Err arm is continue, of type !, which coerces to i32.
How the compiler uses divergence
The compiler tracks which code can be reached. Code after a diverging expression is unreachable, and Rust warns about it.
fn main() {
let x: i32 = loop {
break 7;
};
println!("{x}");
}A loop containing break 7 has type i32. A loop with no break has type !, which is how a server's main loop can be declared as fn run() -> !.
Common errors
- A function that should diverge but can return. If
fn stop() -> !has a path that ends normally, you get a type mismatch error. Every path must panic, exit, return from an outer loop, or loop forever. - Expecting
!as a normal variable type. Using!as the type of a variable or a struct field is not stable. Use it as a function return type. You can also useInfalliblefrom the standard library when you need a type with no values. - Silencing warnings by adding code after a diverging call. The compiler marks it unreachable. Remove it instead.
Exercise
The function below is meant to return a u32. Why does it compile, and what is the type of the None arm?
fn get(v: Option<u32>) -> u32 {
match v {
Some(n) => n,
None => panic!("missing"),
}
}
Show answer
The Some arm has type u32. The None arm calls panic!, which has type !. Because ! coerces to any type, it coerces to u32, so both arms agree and the match has type u32.
Exercise
Write a function die(code: i32) -> ! that prints "fatal" to standard error and exits the process with the given code.
Show answer
fn die(code: i32) -> ! {
eprintln!("fatal");
std::process::exit(code)
}
The last expression is std::process::exit(code), which has type !, so no value is returned and the signature is satisfied.