Applied Intermediate

14  Trait objects

When you want a collection of different types behind one interface, store them as trait objects: Box<dyn Trait>. The right method is picked at runtime.

Step 2 / 2

Implement total_area, which sums the area of a slice of boxed shapes -- a mix of types behind dyn Shape.

Hints
  • You can call .area() on each element even though the concrete types differ.
  • shapes.iter().map(|s| s.area()).sum().
14_trait_objects.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
trait Shape { fn area(&self) -> f64; }
struct Circle { r: f64 }
struct Square { s: f64 }
impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r } }
impl Shape for Square { fn area(&self) -> f64 { self.s * self.s } }

fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
    shapes.iter().map(|s| s.area()).sum()
}