Trait objects and structs

I think the important thing to realize is that the trait object type dyn MyTrait is a separate type from MyStruct. Neither is a sub-type of the other or anything like that, it's just possible to convert between them in certain cases. For example, in the latter example, you first create a Box<MyStruct>, which is then converted into a Box<dyn MyTrait>.

Your first example does not work because there's no conversion for a bare MyStruct to a bare dyn MyTrait. The type dyn MyTrait cannot exist without being behind a pointer in the first place, so it makes no sense to have the conversion.

2 Likes