trait MyTrait {
fn my_f(&self) ;
}
struct A {}
struct B {}
impl MyTrait for A {
fn my_f(&self) {
println!("A.my_f()");
}
}
impl MyTrait for B {
fn my_f(&self) {
println!("B.my_f()");
}
}
struct MyList<T: MyTrait> {
list: Vec<T>
}
fn main() {
let list = MyList {
list: vec![
Box::new(A{}),
Box::new(B{})
]
};
}
我关注了这篇文章,Using Trait Objects That Allow for Values of Different Types
根据这篇文章:
This restricts us to a Screen instance that has a list of components all of type Button or all of type TextField. If you’ll only ever have homogeneous collections, using generics and trait bounds is preferable because the definitions will be monomorphized at compile time to use the concrete types.
On the other hand, with the method using trait objects, one Screen instance can hold a Vec that contains a Box as well as a Box. Let’s look at how this works, and then we’ll talk about the runtime performance implications.
但是这段代码无法编译。
最佳答案
仔细阅读有关 Defining a Trait for Common Behavior 的部分。它定义了Screen
在 list 17-4 中,带有 Vec<Box<dyn Draw>>
:
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
然后它说:
we could have defined the
Screen
struct using a generic type and a trait bound as in Listing 17-6
强调条件“可以”。然后它继续解释为什么使用泛型类型和特征绑定(bind)不起作用:
This (1) restricts us to a
Screen
instance that has a list of components all of typeButton
or all of typeTextField
.[…]
On the other hand, with the method using trait objects (2), one
Screen
instance can hold aVec<T>
that contains aBox<Button>
as well as aBox<TextField>
.
(1) 使用泛型类型和特征绑定(bind)
(2) 即 Box<dyn<Draw>>
关于使用特征对象时,使用rust 具有特征绑定(bind)的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74384687/