std::‎thread::JoinHandle::join return type


The return type of std::thread::JoinHandle::join is

pub type Result<T> = crate::result::Result<T, Box<dyn Any + Send + 'static>>;

What useful things can I do with something of type `Box<dyn Any + Send + 'static>? Should I assume this can be about anything, or is there a way to know what it is?


Best, Oliver

That result indicates if the thread panicked; panic payloads are almost always String or &'static str so you can attempt to downcast the Any type to those.

There's a related example of that here:

It's usually going to be a String or &'static str. Also, you can pass it to resume_unwind.

match thread_handle.join() { // <- waits for the thread to complete or panic
    | Ok(value_returned_by_the_thread_s_closure) => { … },
    | Err(e) => {
        // Thread panicked.
        let err_msg = match (e.downcast_ref::<&str>(), e.downcast_ref::<String>()) {
            | (Some(&s), _) => s,
            | (_, Some(s)) => s,
            | (None, None) => "<No panic info>",
        eprintln!("Thread panicked with: {}", err_msg);
        if … { // <- some potential condition (based off the error message?)
1 Like

Awesome, thanks!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.