downcast_ref is a method on an Error trait object that tries to view the same value as a chosen concrete error type. It returns an Option: Some when the type matches and None otherwise. section 13.2.4 section 21.2
Checking boxed errors
A function can return different errors behind Box<dyn Error>. Test each possible type without assuming which one was stored: for err in errs.iter() { if let Some(my_error) = err.downcast_ref::<MyError>() { println!("Got a MyError!"); } else if let Some(recv_error) = err.downcast_ref::<RecvError>() { println!("Got a RecvError!"); } } The first check succeeds for MyError values; otherwise, the second check can identify RecvError values. section 13.2.4
println!("{errs:#?}");
for err in errs.iter() {
if let Some(my_error) = err.downcast_ref::<MyError>() { #1
println!("Got a MyError!"); #2
} else if let Some(parse_error) = err.downcast_ref::<RecvError>() {
println!("Got a RecvError!");
}
}
}
Browse the focused loop that tests an Error trait object against MyError and RecvError. section 13.2.4
Use downcast_ref when:
- The value is available only through a shared Error trait-object reference. section 13.2.4
- The type match is optional, so handle None instead of assuming the downcast succeeds. section 21.2
- A panic hook needs to inspect a payload implementing Any; for example, it can try downcast_ref::<&str>(). section 21.2
