I have recently seen a code like this:
fn read() -> ! {
unimplemented!()
}
fn read2() {
}
fn main() {
read2();
read();
}
I could not find any information about the !
as return type of fn read()
anywhere so I don't have any idea what is this and what for.
The only thing I have found seems useless for me:
Using ! as a return type indicates to the Rust compiler that this function never returns
I don't understand what it does since omitting the type also says that the function returns nothing (the unit
type actually).
Functions are declared using the fn keyword. Its arguments are type annotated, just like variables, and, if the function returns a value, the return type must be specified after an arrow -> . The final expression in the function will be used as return value.
You can use std::ptr::null_mut() or std::ptr::null() (as required) in those particular instances for FFI.
You have to use return if you want to produce a value other than the final value of the block. The official style, then, is to leave off the return in the trailing position because it's redundant.
Keyword fnA function or function pointer. Functions are the primary way code is executed within Rust. Function blocks, usually just called functions, can be defined in a variety of different places and be assigned many different attributes and modifiers.
Unit ()
is not nothing, it is a type, with one possible value also written ()
.
Furthermore, when a function returns unit (or "nothing" as you say), it actually returns. The Never
type !
specifies that the function never returns, i.e. quits the program.
This is typically the return type of a panic
macro:
let s = match i {
1 => "one",
2 => "two",
_ => panic!("Error"),
}
In this example, note that !
can "take the role" of all the types. The compiler does not complain that one branch has type &str
and another has type !
.
For your information, here is a little history of the Never
type.
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