dyn Trait for trait objects

Minimum Rust version: 1.27

The dyn Trait feature is the new syntax for using trait objects. In short:

  • Box<Trait> becomes Box<dyn Trait>
  • &Trait and &mut Trait become &dyn Trait and &mut dyn Trait

And so on. In code:

  1. #![allow(unused_variables)]
  2. fn main() {
  3. trait Trait {}
  4. impl Trait for i32 {}
  5. // old
  6. fn function1() -> Box<Trait> {
  7. unimplemented!()
  8. }
  9. // new
  10. fn function2() -> Box<dyn Trait> {
  11. unimplemented!()
  12. }
  13. }

That's it!

More details

Using just the trait name for trait objects turned out to be a bad decision.The current syntax is often ambiguous and confusing, even to veterans,and favors a feature that is not more frequently used than its alternatives,is sometimes slower, and often cannot be used at all when its alternatives can.

Furthermore, with impl Trait arriving, "impl Trait vs dyn Trait" is muchmore symmetric, and therefore a bit nicer, than "impl Trait vs Trait".impl Trait is explained here.

In the new edition, you should therefore prefer dyn Trait to just Traitwhere you need a trait object.