How to Use Never Type (!) in Rust

The never type (!) in Rust indicates a function that never returns, used for diverging control flow like panics or infinite loops.

The ! type, known as the never type, represents a function that never returns, such as one that panics or loops infinitely. Use it to annotate functions that diverge, ensuring the compiler understands the code path does not continue.

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

fn main() {
    let x = if true {
        diverge()
    } else {
        5
    };
}