Trait objects and dyn compatibility
Quick answer
A trait object hides the concrete type behind a shared behavior interface. It is useful when a collection or interface needs to work with different types that implement one dyn-compatible trait.
What can be called through dyn
Use a reference such as &dyn Label to borrow a trait object. An owned Box<dyn Label> is another option; Box is a heap-owning pointer covered later. Dispatchable methods must satisfy dyn compatibility rules; generic methods cannot normally be dispatched through dyn. A method marked where Self: Sized may be excluded from that interface.
trait Label { fn label(&self) -> &str; }struct Ticket; struct Pass;impl Label for Ticket { fn label(&self) -> &str { "ticket" } }impl Label for Pass { fn label(&self) -> &str { "pass" } }fn main() { let items: [&dyn Label; 2] = [&Ticket, &Pass]; for item in items { println!("{}", item.label()); }}Expected stdout (not executed):
ticketpassEach element implements the same interface.
trait Format { fn format<T>(&self, value: T); }fn use_object(_: &dyn Format) {}fn main() {}Expected: compilation fails; exact diagnostic not verified.
A generic method cannot be dynamically dispatched this way; redesign the interface or restrict that method to Self: Sized.
Common mistake
Not every trait can be used as dyn Trait; check its method and associated-item requirements.
Try it yourself
Add a third Label implementation and explain why it fits the same array type.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Trait objects and dyn compatibility — practice quiz
Choose one answer per question, then review the explanation.
Does creating `&dyn Named` necessarily allocate on the heap?
Why is a method `fn convert<T>(&self, x: T)` generally not dispatchable through dyn?
Can a `where Self: Sized` method be called through a `&dyn Trait` receiver?