// 定义Drawable trait
trait Drawable {
fn draw(&self);
}
// 定义Circle结构体并实现Drawable trait
struct Circle {
radius: f64,
}
impl Drawable for Circle {
fn draw(&self) {
println!("Drawing a circle with radius {}", self.radius);
}
}
// 定义Rectangle结构体并实现Drawable trait
struct Rectangle {
width: f64,
height: f64,
}
impl Drawable for Rectangle {
fn draw(&self) {
println!("Drawing a rectangle with width {} and height {}", self.width, self.height);
}
}
// 定义泛型结构体ShapeContainer
struct ShapeContainer<T>
where
T: Drawable,
{
shapes: Vec<T>,
}
// 实现draw_all函数
fn draw_all<T>(container: ShapeContainer<T>)
where
T: Drawable,
{
for shape in container.shapes {
shape.draw();
}
}
fn main() {
let circle = Circle { radius: 5.0 };
let rectangle = Rectangle { width: 10.0, height: 5.0 };
let mut container = ShapeContainer {
shapes: Vec::new(),
};
container.shapes.push(circle);
container.shapes.push(rectangle);
draw_all(container);
}