Different types, one interface.
Use dyn when heterogeneous values need a shared behavior.
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.
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());
}
}BUILD LAB ---------
- 1
Each Box owns one concrete value.
- 2
dyn Render permits different implementations in one vector.
- 3
Calling render dispatches through the trait object.
cargo run -p lesson_trait_objects03 Mind the boundary
04 Your next build
Create two implementations of an Area trait and sum their areas through borrowed trait objects.
Reveal one possible solution +
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
Which type permits different Render implementations in one owned vector?
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.