Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use of `!` as return type in Rust? [duplicate]

Tags:

rust

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

like image 817
Victor Polevoy Avatar asked Oct 11 '17 13:10

Victor Polevoy


People also ask

How do you set a return type in Rust?

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.

How do you return a NULL in Rust?

You can use std::ptr::null_mut() or std::ptr::null() (as required) in those particular instances for FFI.

Should you use return in Rust?

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.

What is FN in Rust?

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.


1 Answers

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.

like image 172
Boiethios Avatar answered Nov 30 '22 04:11

Boiethios