In Rust, functions typically return a value, but sometimes you may need to indicate that a function never returns. This is achieved through the ! type (called the never type), which signifies that the function will either loop indefinitely or cause the program to terminate.

What is the ! Return Type

The ! type is a special type in Rust that indicates a function will never return normally; these functions either terminate the program or run forever.

Manually triggering a panic:

fn never_returns() -> ! {
    panic!("This function never returns!");
}

Program exit or termination:

fn exit_program() -> ! {
    std::process::exit(0);
    // std::process::abort();
}

When a function contains an infinite loop, it can be declared to return the ! type because the loop never ends:

fn infinite_loop() -> ! {
    loop {
        println!("Looping forever...");
    }
}