I have the following function that includes some error recovery logic and the process::exit(0)
in the end:
fn gracefully_shutdown() {
// Do some logic for the recover
process::exit(7);
}
I want to call that function in the error case but match
complains about incompatible arms
. But it does not complain when I write it explicitly into a match arm like the following:
fn handle_result(my_result: Result<i32, MyError>) -> i32 {
match my_result {
Ok(val) => val,
//Err(_error) => { process::exit(0); } // Does not complain
Err(_error) => {
gracefully_shutdown();
} // Does complain
}
}
Is it really hard for the compiler to understand that gracefully_shutdown()
contains process::exit(0)
in itself?
I would expect that I could have written the code in this way:
fn handle_result(my_result: Result<i32, MyError>) -> i32 {
match my_result {
Ok(val) => val,
Err(_error) => {
gracefully_shutdown();
}
}
}
Any ideas to make this work?
Playground
The exit() function is used to terminate a process or function calling immediately in the program. It means any open file or function belonging to the process is closed immediately as the exit() function occurred in the program.
In C++, you can exit a program in these ways: Call the exit function. Call the abort function. Execute a return statement from main .
Answer: exit() is a system call which terminates current process. exit() is not an instruction of C language. Whereas, return() is a C language instruction/statement and it returns from the current function (i.e. provides exit status to calling function and provides control back to the calling function).
Return uses exit code which is int value, to return to the calling function. Using the return statement in the main function means exiting the program with a status code; for example, return 0 means returning status code 0 to the operating system.
Change the signature of gracefully_shutdown
to
fn gracefully_shutdown() -> ! {
process::exit(7);
}
This will tell the compiler that this function never returns! The !
is called the never type.
For more information see
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With