What does "-> !" means in Rust

Viewed 1371

Recently I was running across some piece of Rust code and bumped into function that returned "!" instead of basic variable type, like this:

fn my_function() -> ! {
    //function body
}

So I was wondering, what does it mean. I was unable to find piece of information about this in https://doc.rust-lang.org/book What data, function returns with such indicator?

2 Answers

It means the function never returns (usually because it unconditionally panics or otherwise ends the program, or because it contains an infinite loop that prevents a return from ever happening).

The appendix describes it as:

! Always empty bottom type for diverging functions

where "diverging" means "never returns".

To give some additional context:

! is the never type; it's a type that has no possible value, so it can never be created. If a function returns !, this means that it never completes.

Examples:

fn panics() -> ! {
    panic!()
}

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

At the moment, the ! type is unstable, so it can only be used in return position. In the future, when the never type is stabilized, we will be able to write things like Result<T, !> (a result that's never an error).

Note that ! can be coerced to any other type. This means that ! is a subtype of every other type. It is often called the "bottom type" because of this. It means that we are allowed to write, for example:

let x: i32 = if some_condition {
    42
} else {
    panic!("`!` is coerced to `i32`")
};

Since ! doesn't work on stable Rust (except in return position), there's a workaround to get a similar type:

enum Never {}

This enum has no variants, so it can never be created, so it's equivalent to !.

Related