
Any and Downcasting in Rust Trait Objects Explained
std::any::Any lets you ask a trait object what concrete type it holds. Learn downcast_ref, Box<dyn Any>, the as_any pattern for your own traits, and when an enum is the better design.
Tag
7 posts

std::any::Any lets you ask a trait object what concrete type it holds. Learn downcast_ref, Box<dyn Any>, the as_any pattern for your own traits, and when an enum is the better design.

In argument position impl Trait is a generic, in return position it hides one concrete type, and dyn Trait is for several. Here is how to pick in each place.

Static dispatch resolves the call at compile time and dynamic dispatch looks it up in a vtable at run time. See the layout, the cost and when it matters.

Box<dyn Trait> costs one allocation and one indirect call per use. Learn what that costs, when it is worth it and the cheaper alternatives.

Dyn compatibility is the set of rules a trait must meet to be used as dyn Trait. Learn each rule, the error it produces and how to keep a trait usable.

A trait object is a pointer plus a vtable, which lets one Vec hold many types. See how to build one, what the cost is, and why some traits cannot be used this way.

A guide to choosing between generics, impl Trait, trait objects and enums in Rust, with one example solved four ways and the costs of each.