How to cleanly end the program with an exit code?

Building over the comments of @FrancisGagné 's answer, if you are searching for an equivalent of C's return exit_code, you can artificially build it this way:

fn main() {
    let exit_code = real_main();
    std::process::exit(exit_code);
}

fn real_main() -> i32 {
    // the real program here
}

This way, all the objects of your program will be in the scope of the real_main() function, and you can safely use return exit_code; in main while still having all destructors properly run.


Starting with Rust 1.26, main can return any type that implements the Termination trait. The standard library provides implementations on several types, such as Result<(), E> for any type E: Debug. Furthermore, the trait was stabilized in 1.61, allowing third-party crates to implement it for their own types.

For Result values, an Ok value maps to ExitCode::SUCCESS (usually 0) and an Err value maps to ExitCode::FAILURE (usually 1). The error value is also automatically printed to the standard error stream.

If you need to return a specific numeric value, use ExitCode as the return type for main.

use std::process::ExitCode;

fn main() -> ExitCode {
    ExitCode::from(101)
}

std::process::exit exits the program with the specified exit code.

Tags:

Rust