'Why would I use divergent functions?

Reading through the Rust book, I came across an interesting topic — divergent functions:

Rust has some special syntax for ‘diverging functions’, which are functions that do not return:

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

A diverging function can be used as any type:

let x: i32 = diverges();
let x: String = diverges();

What would be the use cases of a divergent function? The book says that

panic!() causes the current thread of execution to crash with the given message. Because this function will cause a crash, it will never return, and so it has the type !

That makes sense, but I can't think of where else a divergent function would be of use and it seems very localized to just panic!. I know there must be some useful scenarios out there for why they introduced divergent functions. Where would I likely see divergent functions in Rust?



Solution 1:[1]

As you quoted from the book, Rust's bottom type is used to specify functions that do not return. This includes:

  • panic!()
  • looping forever
  • quitting the program (except returning from main()), such as exit(), whose signature is pub fn exit(code: i32) -> !

Solution 2:[2]

One of the most common use cases is to enable (custom) panicking in #![no_std] environments:

#![panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop{}
}

You’ll see a lot of diverging functions in Philipp Oppermann’s Rust OS development tutorial because, when you’re working at levels that low, returning will triple-fault the CPU and cause it to reset (or in layman’s terms, cause an immediate reboot).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mdup
Solution 2