Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ REUSE THE IDEA
BUILD NOTE 26 / 53

Different types, one interface.

Use dyn when heterogeneous values need a shared behavior.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

A trait object such as &dyn Trait or Box<dyn Trait> hides a concrete type behind a dynamic dispatch interface. This differs from generic static dispatch and is useful for heterogeneous collections or runtime-selected implementations. Not every trait is dyn-compatible: methods requiring arbitrary generic type parameters or returning an unconstrained Self can prevent object use. Use dynamic dispatch when the flexibility is valuable, not just to avoid understanding the concrete ownership model.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/trait-objects/src/main.rs
trait Render {
    fn render(&self) -> String;
}
struct Heading;
struct Divider;
impl Render for Heading {
    fn render(&self) -> String {
        "BUILD LAB".into()
    }
}
impl Render for Divider {
    fn render(&self) -> String {
        "---------".into()
    }
}
fn main() {
    let blocks: Vec<Box<dyn Render>> = vec![Box::new(Heading), Box::new(Divider)];
    for block in blocks {
        println!("{}", block.render());
    }
}
↳ EXPECTED OUTPUT
BUILD LAB
---------
  1. 1

    Each Box owns one concrete value.

  2. 2

    dyn Render permits different implementations in one vector.

  3. 3

    Calling render dispatches through the trait object.

From the extracted rust-workbench folder
cargo run -p lesson_trait_objects

03 Mind the boundary

04 Your next build

A SMALL MISSION

Create two implementations of an Area trait and sum their areas through borrowed trait objects.

Reveal one possible solution +
solutions/trait-objects/src/main.rs
trait Area {
    fn area(&self) -> u32;
}
struct Square(u32);
struct Rect(u32, u32);
impl Area for Square {
    fn area(&self) -> u32 {
        self.0 * self.0
    }
}
impl Area for Rect {
    fn area(&self) -> u32 {
        self.0 * self.1
    }
}
fn main() {
    let s = Square(3);
    let r = Rect(2, 4);
    let shapes: [&dyn Area; 2] = [&s, &r];
    assert_eq!(shapes.iter().map(|x| x.area()).sum::<u32>(), 17);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Which type permits different Render implementations in one owned vector?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.