Given the following setup:
trait MyTrait {}
struct TraitContainer<T: MyTrait> {
inner: T
}
I want to to create a Vec<TraitContainer<_>>
where each container may have a different trait implementation. The naive way would be to remove the generic param and replace it with Vec<TraitContainer<Box<dyn MyTrait>>>
. But I feel like I shouldn't need to. I want to do something like Vec<Box<dyn TraitContainer<MyTrait>>>
, and it feels like it should be possible, but I don't really know how to make it work.
To put my idea in another context: If I have a Vec<Box<dyn MyTrait>>
, every time I want to access an object, it will do dynamic dispatch to find the correct implementation of the trait. But if I know that all items of my Vec will have the same type (I just don't know the exact one, only that they implement some trait), I should be able to do Box<dyn Vec<MyTrait>>
. That way I still have dynamic dispatch, but moved to the outermost nesting level.