Recover in Rust
In Rust, panic handling is done through the Result
type and the ?
operator for error propagation. However, we can simulate a similar behavior to Go’s recover
using std::panic::catch_unwind
.
In Rust, we use std::panic::catch_unwind
to catch panics. This is somewhat similar to Go’s recover
, but with some important differences:
catch_unwind
is used to catch panics in a specific scope, rather than using a deferred function.- It returns a
Result
, which we can then match on to handle the panic. - Not all panics can be caught by
catch_unwind
, particularly if the panic was caused by stack overflow or if the panic payload isn’t safely unwindable.
The downcast_ref
method is used to try to extract the panic message as a string slice. If successful, we print it; otherwise, we print a generic message.
When you run this program, you’ll see:
This demonstrates that we’ve successfully caught the panic, printed the error message, and continued execution.
It’s important to note that while this pattern can be useful in some scenarios (like in FFI code or for some high-level error handling), it’s generally not recommended to use catch_unwind
for normal error handling in Rust. Instead, Rust encourages using the Result
type for expected error conditions.