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.
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 iss * s.
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 }
}