Created
November 2, 2022 21:24
-
-
Save monadplus/af0566735b4d6763cee046dc8545e91e to your computer and use it in GitHub Desktop.
Rust: UnwindSafe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//! 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