pub trait Draw {
fn draw(&self);
}
pub struct Screen {
pub components: Vec<Box<dyn Draw>>,
}
这个动态数组元素类型使用了新语法Box<dyn Draw>来表示trait对象,它被用来代表所有被放置在Box中且实现了Draw trait的具体类型。
我们同样可以使用带有trait约束的泛型参数来定义结构体,但两者的工作机制截然不同。泛型参数一次只能替代为一个具体的类型,而trait对象则允许你在运行时填入多种不同的具体类型。
pub struct Screen<T: Draw> {
pub components: Vec<T>,
}
如果你需要的仅仅是同质集合(homogeneous collection),那么使用泛型和trait约束就再好不过了,因为这段定义会在编译时被多态化以便使用具体的类型。
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}
run方法只关心值对行为的响应,而不在意component的具体类型。通过在定义动态数组时指定Box<dyn Draw>元素类型,Screen实例只会接收那些能够调用draw方法的值。


















