Why can't `&(?Sized + Trait)` be cast to `&dyn Trait`?

后端 未结 3 2179
死守一世寂寞
死守一世寂寞 2020-12-01 18:47

In the code below it is not possible to obtain a reference to a trait object from a reference to a dynamically-sized type implementing the same trait. Why is this the case?

3条回答
  •  天涯浪人
    2020-12-01 19:10

    Not sure if that solves your concrete problem, but I did solve mine with the following trick:

    I added the following method to FooTrait:

    fn as_dyn(&self) -> &dyn FooTrait;
    

    A default impl can not be provided (because it requires that Self be Sized, but constraining FooTrait to be Sized forbids creating trait objects for it...).

    However, for all Sized implementations, it is trivially implemented as

    fn as_dyn(&self) -> &dyn FooTrait { self }
    

    So basically it constrains all implementations of FooTrait to be sized, except for dyn FooTrait.

    Try it on the playground

提交回复
热议问题