
Understand it
A trait object stores a pointer to data and a table of methods. It enables mixed concrete types in one collection at the cost of dynamic dispatch and some optimization opportunities.
A trait object lets code work with a value whose concrete type is chosen at runtime. Box<dyn Draw> owns a value on the heap while exposing only the Draw behavior. A vector of these boxes can contain buttons, charts, and labels as long as each implements Draw. A generic Vec<T> normally has one concrete T for all entries, so it cannot directly hold several unrelated structs. The trait object is the bridge when a heterogeneous collection is genuinely needed.
At a call to item.draw(), the program follows a method table associated with that value's concrete type. This adds an indirection and can limit some optimizations, but it also means new implementers can join the collection without rewriting the renderer. The object still obeys ownership rules: the vector owns the boxes, and borrowing the slice for render does not consume them. &dyn Draw would borrow a single drawable instead of owning it.
The trait must be usable as an object; not every trait method fits. A method that returns bare Self or is generic over another type may need a where Self: Sized restriction or a different design. Start with a small behavior contract such as draw(&self). Implement it for two types, store both in one vector, and count the calls. Use static generic dispatch when all values have one concrete type known at compile time. Choose dynamic dispatch for the runtime mixture, not as a default for every trait.
Read the code
trait Draw { fn draw(&self); }
fn render(items: &[Box<dyn Draw>]) {
for item in items {
item.draw();
}
}The example makes the contract visible in code.
Try it
Say what render knows about each item, and where the draw call is resolved.
What success looks like: You can explain why one slice can mix types, and what dynamic dispatch costs.
Check your understanding
What does dyn Trait choose at runtime?
Reveal the answer
- The concrete method
- The lifetime
- The crate version
Correct: The concrete method.
Go deeper
Common misconception: “dyn Draw picks the concrete type at compile time, like a generic.”
render is compiled once and does not know the concrete types. At item.draw() the program follows the value's method table, so each element runs its own draw.
- Inspect the element: Each
Box<dyn Draw>owns one value on the heap and points at its method table.renderborrows the slice, so the boxes stay with their owner. - Predict before checking: Implement
DrawforButtonandLabel, then makelet items: Vec<Box<dyn Draw>> = vec![Box::new(Button), Box::new(Label)];. Predict the output ofrender(&items), and whether it can run twice. - Compare with evidence: Each element runs its own
draw, in order. The secondrenderworks because the first only borrowed the slice.
Transfer challenge: Try a Button and a Label in one Vec<T> passed to a function with T: Draw, and read the type mismatch. Then add fn copy_of(&self) -> Self; to Draw and read why dyn Draw is now rejected.
Connections
- Owned or Borrowed?: Choose a return type that matches the data flow
- Blanket Implementations: Implement behavior for every matching type
Learn this lesson with AI
Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.
I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools. Lesson: Trait Objects (courseId "ownership", lessonId "trait-objects") Link: https://crabrix.com/learn/ownership/trait-objects/ Goal: A trait object stores a pointer to data and a table of methods. Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=ownership/trait-objects) and I will write the code there. Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.