Answer#
Both let a function work with "anything that implements a trait". They differ in when the choice is made.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
3.0 * self.0 * self.0 // 3.0 instead of pi, to keep the output short
}
}
// Generic: the compiler makes one copy of the function per type (static dispatch).
fn print_area(shape: &impl Shape) {
println!("area {}", shape.area());
}
// Trait object: one function, the method is looked up at run time (dynamic dispatch).
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
print_area(&Square(2.0));
let mixed: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0)), Box::new(Circle(1.0))];
println!("total {}", total_area(&mixed));
}area 4
total 7The answers below describe the two approaches as separate, complete options.