Search code examples
rust

What is the use of `!` as return type in 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).


Solution

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