Stabilizing Rust's never type
In Rust, the never type is a special type denoted by an exclamation mark (!) that indicates a function never returns or a value can never occur. It has been used internally by the compiler but was considered unstable for a long time. On August 24, after over two years of work, Rust compiler contributor waffle finally stabilized the never type, despite needing a small breaking change to previous Rust editions to avoid impacting much real code.
There are two reasons for the existence of the never type: practical and philosophical. Practically, it allows for more efficient generic code by enabling the compiler to optimize out error branches in functions with infallible conversions. Philosophically, it simplifies type inference by treating infinite loops uniformly. It also automatically coerces to any other type, enabling type-system-driven dead-code elimination.
However, stabilizing the never type required resolving a complex corner case. When converting from the never type to other types, the compiler could sometimes be unable to infer the concrete type of an expression, leading to potential compilation errors. To address this, a special rule was introduced: if an ambiguous type remained after type inference, assume it should be the designated fallback type.
Prior to Rust 2024, this fallback type was the unit type (), and in Rust 2024, it was changed to the never type itself, effectively canceling out the implicit conversion. This change was technically a breaking change, as it could impact code inference for some cases, but the edition system allowed for backporting the new behavior to older editions.
When stabilizing the never type, the standard library's Infallible type, which served the same semantic purpose, was planned to become a type alias for !. However, defining Infallible as ! could unintentionally create breaking changes due to implicit conversions. As both defining Infallible as ! and changing its default fallback type were breaking changes, they nearly canceled each other out, minimizing the impact on existing code.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.