← Back to Tech Radar
Hacker News tech

Stabilizing Rust's Never Type

Trending on Hacker News: Stabilizing Rust's Never Type (88 points / 10 comments, via lwn.net)

In one line

A function’s return type is supposed to indicate the kind of data that it produces. Rust’s ‘n […]

Opening excerpt

(Note: Rust also uses exclamation marks to indicate calls to macros. The way the syntax is constructed, a place where it is valid to use the never type is not a valid place to put a macro invocation and vice versa.)

There are two reasons that Rust has a never type, one practical and one philosophical. The practical reason is that it allows for more efficient generic code. For example, consider the FromStr trait in the standard library, which is used for types that can be instantiated from a string:

trait FromStr: Sized { type Err; fn from_str(s: &str) -> Result<Self, Self::Err>; } FromStr::from_str() either returns a converted result, or a custom error type. For example, attempting to convert “foo” into an integer will return a ParseIntError . But some types have an infallible conversion. For example, it is always possible to convert a string into a ByteString . That implementation of FromStr could set Err to be the never type.

impl FromStr for ByteString { type Err = !; fn from_str(s: &str) -> Result<Self, !> { …

(Excerpted from the original; full article via the source link below.)

This story hit the Hacker News front page today (88 points / 10 comments, via lwn.net). Our Tech Radar aggregates daily signals on AI engineering, backend architecture and DevOps — browse the related services and further reading below, or get in touch with our team.

Source: Hacker News

Related Services

Related Reading