trait Shape {
fn area(&self) -> f64;
}
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
trait AddShape {
fn add(&self, other: &Self) -> Box<dyn Shape>;
}
impl AddShape for Rectangle {
fn add(&self, other: &Self) -> Box<dyn Shape> {
let new_width = self.width + other.width;
let new_height = self.height + other.height;
Box::new(Rectangle {
width: new_width,
height: new_height,
})
}
}
impl AddShape for Circle {
fn add(&self, other: &Self) -> Box<dyn Shape> {
let new_radius = (self.radius * self.radius + other.radius * other.radius).sqrt();
Box::new(Circle {
radius: new_radius,
})
}
}
fn main() {
let rect1 = Rectangle { width: 5.0, height: 3.0 };
let rect2 = Rectangle { width: 2.0, height: 4.0 };
let circle1 = Circle { radius: 3.0 };
let circle2 = Circle { radius: 4.0 };
let mut shapes: Vec<Box<dyn Shape>> = Vec::new();
shapes.push(rect1.add(&rect2));
shapes.push(circle1.add(&circle2));
for shape in shapes {
println!("Area: {}", shape.area());
}
}