Box<dyn Trait> doesn‘t implement the trait

Posted 金庆

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Box<dyn Trait> doesn‘t implement the trait相关的知识,希望对你有一定的参考价值。

Box<dyn Trait> doesn’t implement the trait

From: https://bennetthardwick.com/dont-use-boxed-trait-objects-for-struct-internals/

By default a Box<dyn Trait> doesn’t implement the trait of the object it contains. This means that trying to construct PeopleZoo<Box<dyn Person>> won’t work out of the box and will give a type error.

Because of this, it’s good practice to give a default implementation of your trait for it’s boxed counterpart. This can be done by calling as_ref or as_mut on the Box and calling the references relevant method.

For just a small bit of effort you can help a bunch of people that may consume your struct.

trait Person 
    fn say_hello(&self);


impl Person for Box<dyn Person> 
    fn say_hello(&self) 
        self.as_ref().say_hello()
    


struct PeopleZoo<P: Person> 
    people: Vec<P>,


fn main() 
  let mut zoo: PeopleZoo<Box<dyn Person>> = PeopleZoo 
    people: vec![]
  ;

以上是关于Box<dyn Trait> doesn‘t implement the trait的主要内容,如果未能解决你的问题,请参考以下文章

Box<dyn Trait> doesn‘t implement the trait

rust - 方法 `draw`存在,但在Vec <Box <dyn Trait >>中不满足以下特征范围,Compilernote应该满足吗?

rust特征对象

如何将 Box<dyn Error + Sync + Send> 转换为 Box<dyn Error>

如何使 Rust Generic Struct/Trait 需要 Box<other trait>?

Rust impl trait