liveBook · Manning

Downcast_ref

As explained in Learn Rust in a Month of Lunches

downcast_ref is a method on an Error trait object that attempts to obtain a shared reference to the value as a specified concrete error type.

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

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains the method through boxed-error and panic-hook examples, including its fallible Option result.
Examples
Uses MyError, RecvError, and a panic payload commonly represented as &str.
What it assumes
Assumes familiarity with Rust traits, Box<dyn Error>, trait objects, and Option-based if let handling.
What you can do after
Diagnose errors by conditionally recovering their concrete types from trait objects.
How it connects
Connects Error trait objects, Box, Any, panic hooks, and concrete error types.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.