RRust By Example
advancedFunctions

Diverging Functions

Functions that never return using -> ! (never type).

Diverging Functions

Functions that never return using -> ! (never type).

Difficulty

Advanced

Code

rust
fn exit_with_code(code: i32) -> ! {
    std::process::exit(code);
}

fn forever() -> ! {
    loop {
        // this never returns
    }
}

fn main() {
    let x: i32 = if true {
        42
    } else {
        // exit_with_code(1); // diverges, so type is !
        0 // placeholder
    };
    println!("x = {}", x);

    // panic! also has type !
    // let y: String = panic!("never");
}

Explanation

Functions with -> ! never return.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the functions category to build a complete understanding of this topic.

More Functions Examples