Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does returning "!" mean in Rust?

Tags:

syntax

rust

Recently I came across a function in Rust that returned ! instead of basic type, like this:

fn my_function() -> ! {
    // ...
}

What does it mean? I was unable to find piece of information about this in The Rust Book. What data does this function return with such indicator?

like image 656
dragonhaze Avatar asked Apr 21 '26 15:04

dragonhaze


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".

like image 81
ShadowRanger Avatar answered Apr 23 '26 10:04

ShadowRanger


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 !.

like image 25
Aloso Avatar answered Apr 23 '26 08:04

Aloso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!