Error code E0746
An unboxed trait object was used as a return value.
Erroneous code example:
ⓘ
Return types cannot be dyn Trait
s as they must be Sized
.
To avoid the error there are a couple of options.
If there is a single type involved, you can use impl Trait
:
If there are multiple types involved, the only way you care to interact with
them is through the trait's interface, and having to rely on dynamic dispatch
is acceptable, then you can use trait objects with Box
, or other container
types like Rc
or Arc
:
Finally, if you wish to still be able to access the original type, you can
create a new enum
with a variant for each type:
You can even implement the trait
on the returned enum
so the callers
don't have to match on the returned value to invoke the associated items:
If you decide to use trait objects, be aware that these rely on dynamic dispatch, which has performance implications, as the compiler needs to emit code that will figure out which method to call at runtime instead of during compilation. Using trait objects we are trading flexibility for performance.