quest

Sign in to start training

quest keeps your progress, streaks, and scores tied to your account — so you can pick up on any device.

Synced everywhere. Progress follows you across laptop and phone.
Streaks & stats. See your daily run and every score over time.
Your profile. A name and avatar for the work you do here.

We only use Google to sign you in and sync progress. No posting, no contacts — ever.

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()
}