39. Trait Upcasting — Cast dyn Trait to dyn Supertrait
Since Rust 1.86, you can upcast a trait object to its supertrait — no workarounds needed.
The problem
Imagine you have a trait hierarchy:
| |
Before Rust 1.86, if you had a &dyn Animal, you couldn’t simply cast it to &dyn Any. You’d have to add an explicit method to your trait:
| |
This was boilerplate that every trait hierarchy had to carry around.
The fix: trait upcasting
Now you can coerce a trait object directly to any of its supertraits:
| |
The key line is let any: &dyn Any = animal; — this coercion from &dyn Animal to &dyn Any used to be a compiler error and now just works.
It works with any supertrait chain
Upcasting isn’t limited to Any. It works for any supertrait relationship:
| |
This makes trait object hierarchies much more ergonomic. No more as_drawable() helper methods cluttering your traits.