skip to content

In Rust 2024, why does `parse(raw)?;` with `fn parse<T: Default>(raw: &[u8]) -> Result<T, String>` fail with E0277 on `!: Default`, and how do you fix it?

level: seniorimportance: nice to knowfreq 10%

answer

  1. what a diverging expression becomes
  2. the question mark operator's desugaring
  3. the fallback moved from unit to never
  4. deny-by-default lints since 1.92

basics

~20 s

Rust 2024 changed never-type fallback from () to !. In parse(raw)?; nothing constrains T, so 2021 picked () through the question mark's desugaring, while 2024 picks !, which does not implement Default. Name the type, as in parse::<Header>(raw)?.

solid answer

~50 s

Diverging expressions such as `return`, `panic!()` or the error path of `?` have the never type `!`, which can coerce to any type. When inference finds nothing else to pick, rustc uses a **fallback** type: `()` up to 2021, `!` on the 2024 edition. In `parse(raw)?;` the result is discarded, so `T` is pinned only by that fallback; on 2024 `T = !` and the bound fails: "the trait bound `!: Default` is not satisfied" (E0277). Fix it by naming the type, `parse::<Header>(raw)?`, or by pinning the old one with `parse::<()>(raw)?` or `() = parse(raw)?;`. Closures like `run(|| panic!())` break the same way and need `|| -> () { .. }`. On rustc 1.92 and later, the lints `dependency_on_unit_never_type_fallback` and `never_type_fallback_flowing_into_unsafe` are deny-by-default on every edition, and rustc 1.99's `cargo fix --edition` inserts `::<()>` automatically.

code

rust · 19 lines
rust
#[derive(Debug, Default)]
struct Header;

fn parse<T: Default>(raw: &[u8]) -> Result<T, String> {
    if raw.is_empty() {
        return Err("empty frame".to_string());
    }
    Ok(T::default())
}

fn validate(raw: &[u8]) -> Result<usize, String> {
    parse(raw)?;
    Ok(raw.len())
}

fn main() {
    println!("{:?}", validate(b"abc"));
    println!("{:?}", parse::<Header>(b"x"));
}

go deeper

for a junior

Recall that return, panic! and the error path of the question mark have the never type, and that Rust 2024 changed what an unconstrained one turns into.

for a middle

Explain fallback as the type inference picks when nothing else constrains it, unit before 2024 and never on 2024, and why an unused generic Result exposes it.

for a senior

Show how you fix each breakage by naming the real type, why the unsafe-call case is denied, and why rustc 1.92 and later already reject fallback-dependent code on 2021.

for a principal

Decide whether a team accepts cargo fix's unit annotations or replaces them with real types, and how much blocking on these lints a toolchain upgrade may introduce before the edition switch.

## What never-type fallback is Some expressions never produce a value: `return`, `break`, `continue`, `panic!()`, `loop {}` without a `break`, and the early-return path inside `?`. Their type is the **never type**, written `!`. Because such code never finishes, rustc lets a `!` value **coerce to any type**, which is why `let x: u8 = panic!();` type-checks. Each such coercion leaves a type for inference to determine. Usually the context decides it. When nothing does, rustc picks a **fallback type**: - up to the 2021 edition the fallback is `()`; - on the 2024 edition the fallback is `!` itself. The edition guide says the change is planned for all editions at a later date. Writing `!` as a type in your own signatures is still unstable (the `never_type` feature on nightly); the fallback happens inside inference regardless. ## Why the fallback changed The `()` fallback made `!` silently turn into `()` in places where inference would never otherwise have chosen unit. That surprised readers, hid bugs such as the unsafe case below, and stood in the way of ever stabilising `!` as a type. With `!` as the fallback, a diverging expression with no reason to become anything else simply stays `!`, which is what most people expect it to do. The cost is that code which leaned on the accidental `()` stops compiling, and the edition boundary is where Rust lets that happen. ## Why `parse(raw)?;` breaks ```rust fn parse<T: Default>(raw: &[u8]) -> Result<T, String> { /* ... */ } fn validate(raw: &[u8]) -> Result<usize, String> { parse(raw)?; Ok(raw.len()) } ``` The result of `parse(raw)?` is discarded, so nothing in `validate` says what `T` is. The `?` operator desugars into a `match` whose error arm returns early, a `!`-typed branch, and with no other constraint `T` is left to the fallback. On 2021 that was `()`, and `(): Default` holds, so the code compiled by accident. On 2024 `T` becomes `!`, and rustc 1.99 reports: `error[E0277]: the trait bound `!: Default` is not satisfied` with the help line "you might have intended to use the type `()` here instead". ## Other patterns that break the same way | Pattern | 2024 result | Fix | |---|---|---| | `parse(raw)?;` with an unconstrained generic `T` | E0277, `!: Default` | `parse::<Header>(raw)?` or `() = parse(raw)?;` | | `run(\|\| panic!())` where `run<R: Unit>` and only `()` implements `Unit` | E0277, `!: Unit` | `run(\|\| -> () { panic!() })` | | `if c { Default::default() } else { return };` | E0277, `!: Default` | `() = if c { Default::default() } else { return };` or `<() as Default>::default()` | | `if c { return } else { unsafe { std::mem::zeroed() } };` | Rejected by a deny lint | `std::mem::zeroed::<()>()` | The last row is the dangerous one. With `!` as the fallback, `mem::zeroed()` would be asked to create a value of type `!`, which is undefined behaviour the moment it runs. The `never_type_fallback_flowing_into_unsafe` lint catches fallback reaching an unsafe call like this. ## Migration on a current toolchain Two lints in the `rust-2024-compatibility` group detect these cases on older editions: 1. `dependency_on_unit_never_type_fallback`, for code whose meaning depends on the `()` fallback; 2. `never_type_fallback_flowing_into_unsafe`, for fallback that reaches an unsafe call. The edition guide describes the first as a warning on older editions and the second as deny on 2024. The toolchain has moved further: **Rust 1.92 made both deny-by-default**, and rustc 1.99 reports them as errors on a 2021 crate too, with the note "this was previously accepted by the compiler but is being phased out; it will become a hard error in Rust 2024 and in a future release in all editions". So a 2021 crate that relied on the fallback already fails to build on 1.92 or later unless the lint is allowed. The guide also says there is no automatic fix. On rustc 1.99, though, `cargo fix --edition` applied the compiler's suggestion and rewrote `parse()?;` to `parse::<()>()?;`. That keeps the old meaning, but `()` is rarely the type the code means. Review each insertion: - if the call parses something real, name that type, `parse::<Header>(raw)?`, so the code checks what it claims to check; - if the value really is irrelevant, `()` is honest, and `() = parse(raw)?;` documents it at the call site; - for closures, give the closure an explicit return type rather than changing the callee.

  • Why does a 2021-edition crate already fail on rustc 1.99 if the fallback change belongs to 2024?
    The fallback type itself is still `()` on 2021, but Rust 1.92 made `dependency_on_unit_never_type_fallback` and `never_type_fallback_flowing_into_unsafe` deny-by-default in every edition. Code that depends on the `()` fallback is reported as an error, labelled as previously accepted and being phased out. You can still `allow` the lint, but the warning says it will become a hard error in all editions.
  • Why does never-type fallback matter for unsafe code in particular?
    Generic unsafe functions such as `std::mem::zeroed` or `std::mem::transmute` return whatever type inference asks for. If fallback picks `!`, `zeroed()` would create a value of an uninhabited type, which is undefined behaviour as soon as it runs. That is why the 2024 edition, and since 1.92 every edition, denies `never_type_fallback_flowing_into_unsafe` and asks for an explicit type.

  • Rust 2024 made the never type writable as a stable type
  • Never-type fallback still chooses unit on the 2024 edition
  • A 2021 crate is untouched by the never-type change on current compilers
  • The fix is enabling #![feature(never_type)] in the crate
  • Replacing panic! with unreachable! avoids the fallback

Assumes Rust 1.99; never-type fallback is ! on the 2024 edition (stable since 1.85) and () on older editions, and the two fallback lints have been deny-by-default in all editions since 1.92.