Exit in Rust
Here’s an idiomatic Rust example that demonstrates the concept of program exit:
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 theprocess
module into scope, which contains theexit
function.The
println!("Starting the program");
line will be executed and its output will be seen.We define a closure
_cleanup
that simulates some cleanup work. In Rust, unlike Go’sdefer
, 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):
To see the exit code:
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.
This approach allows for more idiomatic error handling in Rust while still providing a way to exit with a specific status code when necessary.