The "!" type is officially stable
4 minutes read •
The never type, also referred to as !, has existed in the compiler for over a decade.
It spent years stuck behind nightly: you could observe it in error messages and even write fn foo() -> !, but you could not name it anywhere else.
After 10 years, Rust 1.100.0 finally made it stable.
If you want to play with it:
$ rustup update stableWhat is the never type?
! is a type with no values (hence the never name duh).
It represents diverging computations, meaning computations that never resolve to any value.
Since no value of type ! can ever exist, the compiler treats it as a marker for unreachable code.
Expressions that terminate control flow have type !: return, break, continue, panic!, and infinite loops.
This example is taken verbatim from the never type documentation:
fn meow() -> u32 {
let _: ! = return 123;
// code following the `return` is unreachable...
// since it returns from the function
}Why does this typecheck? The return 123 expression returns from the function right there, so the binding never happens and the code after it never runs.
The binding itself is pointless, but it shows that a return expression has type !, and that you can now name that type in a type annotation.
How can we use this type?
Before 1.100.0, if the body of a function returning anything other than () or ! was an infinite loop, the compiler demanded a trailing return value:
use anyhow::Error;
use tokio::io::copy_bidirectional;
use tokio::net::{TcpListener, TcpStream};
use tracing::{debug, warn};
async fn proxy(ln: TcpListener, up: &str) -> Result<(), Error> {
loop {
let (sock, addr) = ln.accept().await?;
debug!("{addr} connected");
if let Err(e) = fwd(sock, up).await {
warn!("{addr} ended: {e:#}");
}
}
Ok(())
}
async fn fwd(mut sock: TcpStream, up: &str) -> Result<(), Error> {
let mut out = TcpStream::connect(up).await?;
copy_bidirectional(&mut sock, &mut out).await?;
Ok(())
}The loop can only exit through ?, which returns early, so the Ok(()) sits after code that never finishes.
But in editions before 2024 the compiler could not express that in stable types.
The type of the loop fell back to (), and () does not match Result<(), Error>, so the compiler required a value at the end of the function, hence the Ok(()) return value.
Now the same function needs nothing after the loop:
async fn proxy(ln: TcpListener, up: &str) -> Result<(), Error> {
loop {
let (sock, addr) = ln.accept().await?;
debug!("{addr} connected");
if let Err(e) = fwd(sock, up).await {
warn!("{addr} ended: {e:#}");
}
}
}Wait, why can we do this?
Version 1.100.0 changes the never type fallback from () to ! across all editions. The infinite loop is now properly typed as !, and ! coerces to any type, including Result<(), Error>.
The function typechecks with nothing after the loop, because there is genuinely nothing left to say.
You can go one step further and make the signature itself honest:
async fn proxy(ln: TcpListener, up: &str) -> Result<!, Error> {
loop {
let (sock, addr) = ln.accept().await?;
debug!("{addr} connected");
if let Err(e) = fwd(sock, up).await {
warn!("{addr} ended: {e:#}");
}
}
}Result<!, Error> declares that the Ok variant can never be constructed, since it would have to hold a value of type !.
The function either returns Err(e) through ?, or it never returns at all. Callers benefit: the compiler knows Ok cannot exist, so they can match without an Ok arm:
match proxy(ln, "127.0.0.1:8080").await {
Err(e) => log_and_exit(e),
}Since Ok can never be constructed, the Err(e) pattern is irrefutable, so callers can even skip the match and bind the error directly:
let Err(e) = proxy(ln, "127.0.0.1:8080").await;
log_and_exit(e)Traits for “!”
You can implement your own traits for !.
At first glance this seems pointless, since many trait methods take self, and calling a method on ! is impossible: no value exists to call it with. The point is to satisfy trait bounds when ! is used as a generic argument.
Say you have an App that may hold a Plugin:
trait Plugin {
fn run(&self);
}
struct App<P: Plugin> {
plugin: Option<P>,
}Before, how it was done:
struct NoPlugin;
impl Plugin for NoPlugin {
fn run(&self) {}
}
let app: App<NoPlugin> = App { plugin: None };App<P: Plugin> demands a type for P that implements the trait, even when the app ships with no plugin at all.
Without ! on stable, there was no empty type to point at. The only way through was to invent a dummy struct whose run does nothing, purely to satisfy the bound.
Now, how we can do something like this:
impl Plugin for ! {
fn run(&self) { *self }
}
let app: App<!> = App { plugin: None };Since ! has no values, you can implement your own traits for it, as long as their methods take some form of self.
The body *self looks alarming but is sound: dereferencing self: &! would produce a value of type !, and no such value can exist, so the code is statically unreachable. It coerces to whatever the method returns, and the compiler is satisfied. No dummy type cluttering the API, and the bound is satisfied for free.
The orphan rule still applies: ! is a primitive type from std, so you cannot implement foreign traits like Debug for it in your own crate.
The good news is that 1.100.0 makes std itself implement the important ones, Clone, Debug, Display, PartialEq, Error, so bounds on types like Result<T, !> are satisfied out of the box.
As a rule of thumb from the standard library docs: if a trait only has methods taking self, &self, or other Self-typed arguments, consider implementing it for !.
Comments
You can comment on this blog post by publicly replying to this post using a Mastodon or other ActivityPub/Fediverse account. Known non-private replies are displayed below.