snippetrustMajor
How to cleanly end the program with an exit code?
Viewed 0 times
programwithhowendtheexitcodecleanly
Problem
Is there a way of returning an exit code in Rust 1.0?
I've tried
There is also this question: Exit Rust program early which is similar but asks about the case when the process has to be exited early.
EDIT: I'm looking for a solution that will also allow the process to tidy up the stack, call destructors, etc.
I've tried
env::set_exit_status(exit_code); but this generates a compiler error.There is also this question: Exit Rust program early which is similar but asks about the case when the process has to be exited early.
EDIT: I'm looking for a solution that will also allow the process to tidy up the stack, call destructors, etc.
Solution
Building over the comments of @FrancisGagné 's answer, if you are searching for an equivalent of C's
This way, all the objects of your program will be in the scope of the
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.Code Snippets
fn main() {
let exit_code = real_main();
std::process::exit(exit_code);
}
fn real_main() -> i32 {
// the real program here
}Context
Stack Overflow Q#30281235, score: 71
Revisions (0)
No revisions yet.