Trait Objects
Generic code chooses a trait's implementation at compile time: each type gets its own copy of the function. But sometimes the type becomes known only at run time: circles and squares sit in one vector, event handlers come from different modules, a function returns an error of one of a dozen types. For this Rust has the trait object dyn Trait — a value of "some type with this trait" behind a pointer. A method call goes through the virtual method table, whose address is stored in the second word of a fat pointer.
Not every trait fits dyn: a method must be one function that can be called without knowing the type. This rule is called dyn compatibility; it used to be called object safety. Choosing between generics, dyn and an enum is a frequent question about the cost of abstractions.
The second half of the topic covers trait features you need even without dyn: associated types such as Iterator::Item, operator overloading through the std::ops traits, the orphan rule that forbids implementing a foreign trait for a foreign type, the newtype wrapper as the workaround, and supertraits — one trait's requirement on another. The topic builds on Generics and Traits and walks through the material layer by layer — from dyn Trait to supertraits.
Topic map
- dyn Trait — an unsized type only behind a pointer:
&dyn,Box<dyn>,Rc<dyn>; a 16-byte fat pointer with the vtable's address; the default'staticinBox<dyn Trait>; only auto traits on top, E0225. - Dyn Compatibility — why generic methods,
Selfin the result, functions withoutself, constants andasync fnbreak the method table; E0038; thewhere Self: Sizedworkaround andclone_boxinstead ofClone. - Static vs Dynamic Dispatch — a direct call and inlining versus an indirect call; a homogeneous
&[T]versus a mixedVec<Box<dyn Trait>>; an enum as the third way. - Associated Types — one implementation per type versus a
Trait<T>family;Iterator<Item = u32>in bounds; the mandatoryItemindyn Iterator, E0191; E0283 with a generic trait. - Operator Overloading —
Add,Mul<Rhs>,Output,AddAssign,Neg,Index; moved operands and an implementation for&T; comparisons instd::cmp;&&and||cannot be overloaded. - Orphan Rule and Newtype — coherence of implementations; what is allowed, E0117 and E0210; a zero-cost wrapper; a
typealias does not help. - Supertraits —
trait Pet: Animalas a requirement, not inheritance; supertrait methods in the vtable; upcasting&dyn Pet→&dyn Animalsince Rust 1.86; the full form<T as Trait>::method, E0034.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Declaring Vec<dyn Shape> or a by-value dyn Shape parameter | error[E0277]: the size for values of type `(dyn Shape + 'static)` cannot be known at compilation time — a trait object lives only behind a pointer |
Making a Box<dyn Clone> or using a trait with a generic method as dyn | error[E0038]: the trait `Clone` is not dyn compatible — you need where Self: Sized or a clone_box method |
Passing a &Box<dyn Shape> where a &dyn Shape is expected | error[E0277]: the trait bound `Box<dyn Shape>: Shape` is not satisfied — take a reference to the contents with as_ref() |
Writing Box<dyn Iterator> without the element type | error[E0191]: the value of the associated type `Item` in `Iterator` must be specified |
Implementing Add for a non-Copy type and using an operand after a + b | error[E0382]: borrow of moved value: `a` — implement Add for &T |
Getting around the orphan rule with an alias type Names = Vec<String> | The same E0117: an alias is not a new type, you need a wrapper struct |
| Implementing a subtrait and forgetting the supertrait | error[E0277]: the trait bound `Dog: Animal` is not satisfied |
Why it matters in interviews
Trait objects belong to the middle and senior sections: the candidate is expected to have not syntax but a model — what sits in a fat pointer, how the method table is built and why the dyn compatibility rules follow from it. The choice between generics and dyn, and the difference between an associated type and a generic parameter, are asked almost every time.
What interviewers usually check:
- How a trait object is laid out: a fat pointer of a data address and a vtable address, what the table holds and how this differs from C++.
- What makes a trait dyn compatible, why generic methods and
Selfbreak it, and howwhere Self: Sizedhelps. - When to choose generics, when
dyn, when an enum, and what a dynamic call really costs. - How an associated type differs from a generic trait parameter and why
Iterator::Itemis associated. - What the orphan rule is, why it exists and how to implement a foreign trait for a foreign type through a newtype.
- How a supertrait differs from inheritance and how to call a method when two traits clash on its name.