In Rust 1.27.0 a new syntax is introduced - the dyn
keyword was added.
// old => new Box<Foo> => Box<dyn Foo> &Foo => &dyn Foo &mut Foo => &mut dyn Foo
What does it actually do and why was it added?
The dyn keyword is used to highlight that calls to methods on the associated Trait are dynamically dispatched. To use the trait this way, it must be 'object safe'. Unlike generic parameters or impl Trait , the compiler does not know the concrete type that is being passed. That is, the type has been erased.
A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of an object safe base trait plus any number of auto traits. Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.
This helps differentiate between traits/trait objects and structs; &Foo
, Box<Foo>
and impl Bar for Foo
were ambiguous, because in all of them Foo
could have been a trait or a struct.
With the addition of dyn
this is no longer ambiguous, as traits are distinguished by the dyn
keyword:
// trait objects (new dyn syntax) &Foo => &dyn Foo &mut Foo => &mut dyn Foo Box<Foo> => Box<dyn Foo> // structs (no change) &Bar &mut Bar Box<Bar>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With