trait Drawable {
fn draw(&self);
}
struct Circle {
radius: f32,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle with radius {}", self.radius);
}
}
struct Rectangle {
width: f32,
height: f32,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
}
}
// 使用类型别名简化处理集合的代码
type DrawableList<'a> = Vec<&'a dyn Drawable>;
fn draw_all(drawables: &DrawableList) {
for drawable in drawables {
drawable.draw();
}
}
fn main() {
let circle = Circle { radius: 5.0 };
let rectangle = Rectangle { width: 10.0, height: 5.0 };
let mut drawables: DrawableList = Vec::new();
drawables.push(&circle);
drawables.push(&rectangle);
draw_all(&drawables);
}