金庆的专栏

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  423 随笔 :: 0 文章 :: 454 评论 :: 0 Trackbacks

 From: Don't use boxed trait objects (bennetthardwick.com)

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![] }; }
posted on 2021-12-21 15:09 金庆 阅读(191) 评论(0)  编辑 收藏 引用 所属分类: 8. Rust

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理