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:
- We use - use std::process;to bring the- processmodule into scope, which contains the- exitfunction.
- The - println!("Starting the program");line will be executed and its output will be seen.
- We define a closure - _cleanupthat 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.
- process::exit(3);immediately terminates the program with exit code 3. Any code after this line will not be executed.
- The last - println!statement will never be reached or executed.
To run this program:
- Save the code in a file named exit_example.rs.
- 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 programTo see the exit code:
$ cargo run --bin exit_example
Starting the program
$ echo $?
3Note 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.