liveBook · Manning

Downcasting

As explained in Idiomatic Rust

Downcasting is converting a value from a general type to a more specific compatible type, typically subject to runtime validation.

Trait objects expose only the methods declared by their trait. Downcasting can recover a concrete type when you need to call one of its other methods. To obtain a reference, add an `as_any(&self) -> &dyn Any` method to the trait and implement it by returning `self`. section 2.2.6

Call `downcast_ref::<T>()` on the returned `Any` reference; it yields an optional reference to the value if its concrete type is `T`. `Any` requires `'static` types. Box, Rc, and Arc also support consuming downcasts, while `Any` allows borrowing. Use this escape hatch carefully rather than relying on concrete-type checks throughout dynamic dispatch. section 2.2.6

println!("With a downcast:");
v.iter().for_each(|i| {           #1
    if let Some(obj) = i.as_any().downcast_ref::<MyStruct1>() {
        obj.struct_hello();
    }
    if let Some(obj) = i.as_any().downcast_ref::<MyStruct2>() {
        obj.struct_hello();
    }
});

The example checks each trait object for two concrete types and calls the matching type-specific method. section 2.2.6

How Idiomatic Rust covers it

How deep it goes
Explains `Any`, `as_any`, and borrowed versus consuming downcasts, while cautioning against overuse.
Examples
Demonstrates checking a vector of boxed trait objects for `MyStruct1` or `MyStruct2` and calling type-specific methods.
What it assumes
Assumes familiarity with Rust traits and trait objects; downcasting through `Any` requires `'static` types.
What you can do after
Apply it via `Any` and an `as_any` trait method to obtain a reference to a matching concrete type.
How it connects
Connects trait objects and dynamic dispatch with `Any`, `Box`, `Rc`, and `Arc`.

Also explained in

Compare how 2 books explain downcasting →

Related concepts

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