Dynamic Dispatch with Box<dyn Trait>
10 points
Implement total_area, which sums the areas of a slice of mixed shape types. This is exactly the case static dispatch cannot express — Vec<T> needs one concrete T, so the slice element type has to be Box<dyn Shape>, resolved through a vtable at each .area() call instead of at compile time.
Required signature
pub trait Shape { fn area(&self) -> f64; } pub struct Circle { pub radius: f64 } impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.radius * self.radius } } pub struct Square { pub side: f64 } impl Shape for Square { fn area(&self) -> f64 { self.side * self.side } } pub fn total_area(shapes: &[Box]) -> f64;
Your solution
Log in to submit a solution.