Exit in Rust

Here’s an idiomatic Rust example that demonstrates the concept of program exit:

use std::process;

fn main() {
    // This println! will be executed
    println!("Starting the program");

    // This closure will not be run when using process::exit
    let _cleanup = || {
        println!("Cleaning up resources");
    };

    // Exit with status code 3
    process::exit(3);

    // This line will never be reached
    println!("This won't be printed");
}

This Rust program demonstrates how to exit a program immediately with a given status code. Let’s break down the key points:

  1. We use use std::process; to bring the process module into scope, which contains the exit function.

  2. The println!("Starting the program"); line will be executed and its output will be seen.

  3. We define a closure _cleanup that simulates some cleanup work. In Rust, unlike Go’s defer, there’s no built-in mechanism to automatically run code on exit. The closure is prefixed with an underscore to silence the unused variable warning.

  4. process::exit(3); immediately terminates the program with exit code 3. Any code after this line will not be executed.

  5. The last println! statement will never be reached or executed.

To run this program:

  1. Save the code in a file named exit_example.rs.
  2. Compile and run the program using Cargo (Rust’s package manager and build system):
$ cargo run --bin exit_example
   Compiling exit_example v0.1.0 (/path/to/your/project)
    Finished dev [unoptimized + debuginfo] target(s) in 0.62s
     Running `target/debug/exit_example`
Starting the program

To see the exit code:

$ cargo run --bin exit_example
Starting the program
$ echo $?
3

Note that the cleanup closure was never called, and “This won’t be printed” doesn’t appear in the output.

In Rust, unlike C or Go, the main function can return a Result to indicate success or failure, which is often preferred over using process::exit(). However, process::exit() is useful when you need to terminate the program immediately from any point in your code.

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Your code here
    Ok(())
}

This approach allows for more idiomatic error handling in Rust while still providing a way to exit with a specific status code when necessary.