trait Drawable {
fn draw(&self);
}
enum Shape {
Circle(f64),
Rectangle(f64, f64),
}
impl Drawable for Shape {
fn draw(&self) {
match self {
Shape::Circle(radius) => println!("Drawing a circle with radius {radius}"),
Shape::Rectangle(width, height) => println!("Drawing a rectangle with width {width} and height {height}"),
}
}
}
fn draw_shapes(shapes: &Vec<Box<dyn Drawable>>) {
for shape in shapes {
shape.draw();
}
}
fn main() {
let mut shapes: Vec<Box<dyn Drawable>> = Vec::new();
shapes.push(Box::new(Shape::Circle(5.0)));
shapes.push(Box::new(Shape::Rectangle(10.0, 5.0)));
draw_shapes(&shapes);
}
说明
- 定义
trait
Drawable
:包含draw
方法,这是所有可绘制对象需要实现的方法。
- 定义枚举
Shape
:包含Circle
和Rectangle
两种变体,分别携带半径、宽和高的信息。
- 在
Shape
上实现Drawable
trait:draw
方法通过match
语句根据不同的形状变体打印相应的绘制信息。
- 定义
draw_shapes
函数:接受一个Vec<Box<dyn Drawable>>
参数,遍历向量并调用每个对象的draw
方法。这里使用&Vec<Box<dyn Drawable>>
避免所有权转移,提高性能。
- 在
main
函数中:创建不同形状的实例并放入向量,调用draw_shapes
函数进行绘制。使用Box<dyn Drawable>
实现动态分发,并且在draw_shapes
函数参数中使用引用,减少不必要的内存拷贝,优化内存管理和动态分发性能。