Skip to content

Instantly share code, notes, and snippets.

@eduardonunesp
Created January 12, 2023 17:16
Show Gist options
  • Save eduardonunesp/76124227c121d876a4aa2bd9cd12da18 to your computer and use it in GitHub Desktop.
Save eduardonunesp/76124227c121d876a4aa2bd9cd12da18 to your computer and use it in GitHub Desktop.
Downcast to `&'static str ` an error returned on join thread
use std::thread;
fn main() {
let numbers: Vec<usize> = vec![];
let t = thread::spawn(move || {
let len = numbers.len();
let sum = numbers.into_iter().sum::<usize>();
sum / len
});
let avg = match t.join() {
Ok(v) => format!("{}", v),
Err(err) => {
match err.downcast_ref::<&'static str>() {
Some(s) => *s,
None => match err.downcast_ref::<String>() {
Some(s) => &s[..],
None => "Sorry, unknown payload type",
},
}.to_string()
},
};
println!("{:?}", avg);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment