Expand description
dyn is a prefix of atrait object’s type.
Thedyn keyword is used to highlight that calls to methods on the associatedTraitaredynamically dispatched. To use the trait this way, it must bedyn compatible1.
Unlike generic parameters orimpl Trait, the compiler does not know the concrete type thatis being passed. That is, the type has beenerased.As such, adyn Trait reference containstwo pointers.One pointer goes to the data (e.g., an instance of a struct).Another pointer goes to a map of method call names to function pointers(known as a virtual method table or vtable).
At run-time, when a method needs to be called on thedyn Trait, the vtable is consulted to getthe function pointer and then that function pointer is called.
See the Reference for more information ontrait objectsanddyn compatibility.
§Trade-offs
The above indirection is the additional runtime cost of calling a function on adyn Trait.Methods called by dynamic dispatch generally cannot be inlined by the compiler.
However,dyn Trait is likely to produce smaller code thanimpl Trait / generic parameters asthe method won’t be duplicated for each concrete type.
Formerly known asobject safe. ↩