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?
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 !.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With