In Rust, why does a `match` arm that runs `return Err(...)` type-check beside an arm yielding a `u16`, and what is the type `!`?
answer
- computations that never finish
- a type with no values
- coerces to whatever is expected
- return, panic!, continue, endless loop
- writable only as a return type
basics
~20 sreturn, panic!, continue and an endless loop have the never type !, which has no values, so it coerces to whatever type the other arms need. On stable Rust, ! is written only as a return type.
solid answer
~40 sThe never type `!` is the type of an expression that cannot complete: `return`, `break`, `continue`, `panic!` and its relatives `todo!`, `unreachable!` and `unimplemented!`, a `loop` with no `break`, and calls to functions declared `-> !` such as `std::process::exit`. Because no value of type `!` can exist, the Reference lets an expression of that type coerce to any type. In `let port: u16 = match raw.parse() { Ok(p) => p, Err(e) => return Err(e.to_string()) };` the `Err` arm therefore unifies with `u16`, while at run time control leaves the function instead. A block whose every path diverges also has type `!`, so `fn fail(msg: &str) -> !` may end in `std::process::exit(2)`. On stable, `let x: ! = ...` is E0658.
code
rust · 3 linesfn main() {
let x: ! = panic!("never");
}go deeper
Recall that return, panic! and continue can sit in an arm that is supposed to produce a value, because control never comes back from them.
Explain that these expressions have the never type, which has no values and so coerces to any type, and that -> ! marks a function that never returns.
Explain the diverging-block rule, why a final () after loop {} breaks a -> ! body, and why stable code reaches for Infallible instead of writing !.
Use -> ! deliberately for fatal-exit helpers so their call sites type-check cleanly, and know the 2024 edition's fallback change when migrating code that relied on ().
## A type with no values The Reference defines the **never type** `!` as "a type with no values, representing the result of computations that never complete". Two rules make it useful: - **Coercion:** "Expressions of type `!` can be coerced into any other type." Since an expression of type `!` never produces a value, pretending it produced a `u16`, a `String` or anything else can never be observed, so the coercion is sound. - **Restriction:** "The `!` type can only appear in function return types presently." Writing it anywhere else, such as `let x: ! = ...`, is unstable. ## Which expressions diverge An expression **diverges** when control never reaches the point just after it. The common ones in everyday Rust: 1. `return expr`, which leaves the function. 2. `break` and `continue`, which jump within a loop (loops themselves belong with control flow). 3. `panic!(...)` and the macros built on it: `todo!()`, `unimplemented!()` and `unreachable!()`. 4. `loop { ... }` with no `break` that leaves it. 5. A call to a function declared `-> !`, such as `std::process::exit` or `std::process::abort`. ## Coercion: why the arms agree A `match` or `if` needs one type for the whole expression. When one arm is `p` (a `u16`) and the other is `return Err(...)` (type `!`), rustc coerces the `!` arm to `u16` and the expression is a `u16`. At run time the `Err` arm never yields anything: the function returns before the `let` completes. ```rust fn parse_port(raw: &str) -> Result<u16, String> { let port: u16 = match raw.trim().parse() { Ok(p) => p, Err(e) => return Err(format!("bad port {raw:?}: {e}")), }; let port = if port == 0 { panic!("port 0 is reserved") } else { port }; Ok(port) } fn fail(msg: &str) -> ! { eprintln!("fatal: {msg}"); std::process::exit(2) } fn main() { println!("{:?}", parse_port("8080")); println!("{:?}", parse_port("http")); let mut ok = Vec::new(); for raw in ["443", "x", "80"] { let p: u16 = match raw.parse() { Ok(p) => p, Err(_) => continue, }; ok.push(p); } let first: u16 = if ok.is_empty() { fail("no ports") } else { ok[0] }; println!("{ok:?} {first}"); } ``` It prints the two results on stdout and then the ports: ```plaintext Ok(8080) Err("bad port \"http\": invalid digit found in string") [443, 80] 443 ``` Every line that type-checks here does so through the same coercion: - `Err(e) => return Err(...)` agrees with `Ok(p) => p`. - `if port == 0 { panic!(...) } else { port }` is a `u16`. - `Err(_) => continue` skips the bad entry while the `match` still produces a `u16`. - `if ok.is_empty() { fail("no ports") } else { ok[0] }` works because `fail` is declared `-> !`. ## Diverging blocks and `-> !` functions A block is diverging when "all reachable control flow paths contain a diverging expression", and a diverging block with no final operand has type `!` rather than `()`. That is why the body of `fail` may end in `std::process::exit(2)`, and why `fn f() -> ! { loop {}; }` compiles. A final operand changes the answer: `fn f() -> ! { loop {}; () }` fails with E0308, expected `!`, found `()`, because the block's type now comes from that `()`, even though the line is unreachable (rustc also warns about the unreachable expression). | Expression | Type | Can it coerce to `u16`? | |---|---|---| | `p` where `p: u16` | `u16` | it already is one | | `return Err(e)` | `!` | yes | | `panic!("...")`, `todo!()` | `!` | yes | | `continue` inside a loop | `!` | yes | | `loop {}` with no `break` | `!` | yes | | `()` | `()` | no, E0308 | ## Writing `!` yourself On stable Rust 1.99 you may write `!` only as a function's return type. Anywhere else rustc stops: ```plaintext error[E0658]: the `!` type is experimental --> e15.rs:2:12 | 2 | let x: ! = panic!("never"); | ^ | = note: see issue #35121 <https://github.com/rust-lang/rust/issues/35121> for more information ``` Where an API needs an impossible error type today, std uses `std::convert::Infallible`, an enum with no variants: `<String as FromStr>::Err` is `Infallible`, because turning a `&str` into a `String` cannot fail. When nothing in the code fixes the type a diverging expression should coerce to, the compiler picks a fallback type, and the 2024 edition changed that fallback from `()` to `!`; the 2024 edition material covers what that breaks.
- In Rust, why does `let p: u16 = match raw.parse() { Ok(p) => p, Err(_) => continue };` compile inside a `for` loop?`continue` is a diverging expression of type `!`: control jumps to the next iteration and never reaches the end of that arm. Because `!` coerces to any type, the `Err` arm unifies with the `u16` from `Ok(p) => p`, and the `let` only completes on the `Ok` path. The same works with `break` or `return`.
- In Rust, what is `std::convert::Infallible`, and where does std use it in place of `!`?`Infallible` is an enum with no variants, so, like `!`, no value of it can exist. Its documentation says it "has the same role as" the never type, and since `!` cannot be written there on stable, std uses it where a conversion cannot fail: `<String as FromStr>::Err` is `Infallible`, so `"text".parse::<String>()` returns a `Result` whose `Err` case can never happen.
- `panic!` returns `()`, so its match arm needs a dummy value of the right type.
- The never type `!` is just another spelling of the unit type `()`.
- Stable Rust lets you annotate a local variable as `let x: !`.
- A `return` inside a `match` arm is a type error because that arm produces no `u16`.
- `std::process::exit` returns `()`, like any other side-effecting call.