Rust

Trait Objects (dyn Trait)

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
When you need a heterogeneous collection — different concrete types behind one trait — use `Box<dyn Trait>`. Costs one indirection (vtable) but enables polymorphism that `impl Trait` can't.
Rust
Raw
trait Shape {
    fn area(&self) -> f64;
}

struct Circle    { radius: f64 }
struct Rectangle { w: f64, h: f64 }
struct Triangle  { base: f64, height: f64 }

impl Shape for Circle    { fn area(&self) -> f64 { std::f64::consts::PI * self.radius.powi(2) } }
impl Shape for Rectangle { fn area(&self) -> f64 { self.w * self.h } }
impl Shape for Triangle  { fn area(&self) -> f64 { 0.5 * self.base * self.height } }

fn main() {
    // A vec of mixed shapes — only possible behind a trait object
    let shapes: Vec<Box<dyn Shape>> = vec![
        Box::new(Circle    { radius: 3.0 }),
        Box::new(Rectangle { w: 4.0, h: 5.0 }),
        Box::new(Triangle  { base: 3.0, height: 4.0 }),
    ];

    let total: f64 = shapes.iter().map(|s| s.area()).sum();
    println!("total area: {total:.2}");      // total area: 54.27
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.