trait Shape {
fn area(&self) -> f64;
}
struct Circle { radius: f64 }
struct Rectangle { w: f64, h: f64 }
struct Triangle { base: f64, height: f64 }
impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius.powi(2) } }
impl Shape for Rectangle { fn area(&self) -> f64 { self.w * self.h } }
impl Shape for Triangle { fn area(&self) -> f64 { 0.5 * self.base * self.height } }
fn main() {
// A vec of mixed shapes — only possible behind a trait object
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { radius: 3.0 }),
Box::new(Rectangle { w: 4.0, h: 5.0 }),
Box::new(Triangle { base: 3.0, height: 4.0 }),
];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("total area: {total:.2}"); // total area: 54.27
}
Create a free account and build your private vault. Share publicly whenever you want.