Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created November 2, 2022 21:24
Show Gist options
  • Save monadplus/af0566735b4d6763cee046dc8545e91e to your computer and use it in GitHub Desktop.
Save monadplus/af0566735b4d6763cee046dc8545e91e to your computer and use it in GitHub Desktop.
Rust: UnwindSafe
//! https://doc.rust-lang.org/std/panic/fn.catch_unwind.html
use std::panic::UnwindSafe;
use rand::random;
struct Boxed<'a, T> {
inner: &'a mut [T],
}
impl<'a, T> UnwindSafe for Boxed<'a, T> {}
fn bad<'a, T>(t: Boxed<'a, T>) -> &'a mut T {
if random::<f32>() <= 1.0 {
panic!("I failed on purpose.");
} else {
t.inner.get_mut(0).unwrap()
}
}
fn main() {
let boxed = Boxed {
inner: &mut [1, 2, 3],
};
match std::panic::catch_unwind(|| bad(boxed)) {
Ok(r) => println!("Ok = {r}"),
Err(err) => println!("Err = {err:?}"),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment