admin管理员组文章数量:1636906
Box<dyn Trait>
doesn’t implement the trait
From: https://bennetthardwick/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 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729235050a1191895.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论