liveBook · Manning

Downcasting

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

How 2 Manning books explain it

Learn Rust in a Month of Lunches

Downcasting is the attempted conversion of a dynamically typed or trait-object value back to a specific concrete type.

How it is used
Uses downcasting to recover specific error types from Box<dyn Error> values when generic formatting is insufficient.
How deep it goes
Explains trait-object type erasure and demonstrates downcast_ref across two error types, while not developing downcast ownership details.
Examples
Uses boxed MyError and RecvError values, then checks them with downcast_ref and prints the matching type.
What you can do after
Diagnose boxed errors by testing one known concrete type at a time and handling successful matches.

Read how Learn Rust in a Month of Lunches explains downcasting →

Idiomatic Rust

How it is used
Recovers a concrete type from a trait object when trait methods alone are insufficient.
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 you can do after
Apply it via `Any` and an `as_any` trait method to obtain a reference to a matching concrete type.

Read how Idiomatic Rust explains downcasting →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.