Never

From Rust Community Wiki
Jump to navigation Jump to search

The neverThis links to official Rust documentation type, also called uninhabited type, indicated with an exclamation point (!) is a primitive type that has no values. The never type can never exist at runtime, because it cannot be constructed. It is the return type of divergent functions, which never return:

fn doesnt_return() -> ! {
    loop {}
}

Using ! in other places than the return type of a function, is experimental and requires the never_type nightly feature. A workaround is to use an enum with no variants:

enum Never {}

The standard library contains a similar type, InfallibleThis links to official Rust documentation, which is used as the error type for conversions that never fail. For example:

struct Foo;
struct Bar;

impl TryFrom<Foo> for Bar {
    type Error = Infallible;
    
    fn try_from(_: Foo) -> Result<Bar, Infallible> {
        Ok(Bar)
    }
}

When the never_type feature is stabilized, it will be possible to replace Infallible with ! everywhere. Note that this is a zero-cost abstraction thanks to Rusts layout optimizations.

! is a bottom type, which means that it is a subtype of every other type, and can be coerced to any type. This is exploited when using todo!This links to official Rust documentation or another panicking macro, which evaluates to !:

enum Never {}

fn not_implemented() -> f32 {
    todo!()
}

fn main() {
    let x: Never = panic!();
}

! has no impact on type inference. When no type is explicitly specified, Rust infers the unit type (), which becomes apparent in some error messages:

let x = panic!();
x + 5;

error[E0277]: cannot add `i32` to `()` | 2 | x + 5; | ^ no implementation for `() + i32` | = help: the trait `std::ops::Add<i32>` is not implemented for `()`

! implements many traits from the standard library, to make it easier to use it in generic contexts.