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 1 / 2

Implement the Shape trait for both Circle and Square so each reports its area.

Hints
  • impl Shape for Circle { fn area(&self) -> f64 { ... } }.
  • Circle area is PI * r * r; square area is s * s.
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 }
}