Trait Objects and Advanced Traits
`dyn Trait` and vtables, dyn compatibility, static vs dynamic dispatch, associated types, operator traits, the orphan rule and supertraits.
8 questions
JuniorTheoryCommonWhat is a dyn Trait trait object, and why must it sit behind & or Box?
What is a dyn Trait trait object, and why must it sit behind & or Box?
dyn Shape is a value of some type implementing Shape; which type is known only at run time. Its size is unknown (it is not Sized), so it lives behind &dyn or Box<dyn>, and that is how Vec<Box<dyn Shape>> mixes circles and squares.
Common mistakes
- ✗Writing
Vec<dyn Shape>or a by-valuedyn Shapeparameter, which fails with E0277 because the size is unknown - ✗Thinking
dyn Traitis resolved at compile time, like a generic parameter - ✗Expecting each struct to carry a hidden vtable field, as C++ objects do
Follow-up questions
- →Why does
&dyn Shapetake 16 bytes on a 64-bit target while&Squaretakes 8? - →Why does passing a
&Box<dyn Shape>where&dyn Shapeis expected fail to compile?
MiddleTheoryCommonStatic vs dynamic dispatch: how do you choose between generics and dyn Trait?
Static vs dynamic dispatch: how do you choose between generics and dyn Trait?
Generics are monomorphized: a copy per type, direct inlinable calls, but one type per collection and a bigger binary. dyn Trait keeps one copy and calls via a vtable, losing inlining but mixing types. Default to generics; dyn is for open sets.
Common mistakes
- ✗Trying to put different types into a
Vec<T>with a genericT - ✗Calling
dynslow, though the indirect call is cheap and the real loss is inlining in hot code - ✗Treating
impl Traitas dynamic dispatch, though it stands for one hidden static type
Follow-up questions
- →When would an enum beat both generics and
dyn Traitfor a closed set of types? - →Why does
Box<dyn Error>suit an application's error type better than a generic?
SeniorTheoryCommonHow is a Rust trait object laid out, and what does a dyn method call cost?
How is a Rust trait object laid out, and what does a dyn method call cost?
&dyn Trait is a fat pointer: data plus a static per-(type, trait) vtable with drop, size, alignment and method addresses. Unlike C++, the object holds no vptr. A call loads an address and jumps; the real cost is the lost inlining.
Common mistakes
- ✗Assuming the vtable pointer lives inside the object, as the C++ vptr does
- ✗Forgetting that the vtable also carries the drop function, size and alignment
- ✗Blaming the indirect jump for the cost, when the bigger loss is inlining
Follow-up questions
- →Why can the same
Circlestruct be used directly and asdyn Shapeat no layout cost? - →What does
size_of::<Box<dyn Shape>>()return on a 64-bit target, and why?
JuniorCodeOccasionalImplement Add and AddAssign so that p1 + p2 and p += q work for Point
Implement Add and AddAssign so that p1 + p2 and p += q work for Point
Implement std::ops::Add with type Output = Point; and fn add(self, other: Point) -> Point summing the fields, then AddAssign with fn add_assign(&mut self, other: Point). Output is what + returns; += is its own trait.
Common mistakes
- ✗Expecting
impl Addto make+=work too, thoughAddAssignis a separate trait - ✗Leaving out
type Output, which everyAddimplementation must declare - ✗Looking for
#[derive(Add)]in the standard library, which has none
Follow-up questions
- →What would
p1 + p2do top1ifPointwere notCopy? - →How would you make both
p * 2and2 * pcompile forPoint?
MiddleTheoryOccasionalWhen should a trait use an associated type rather than a generic parameter?
When should a trait use an associated type rather than a generic parameter?
An associated type allows one impl per type, so the output is unambiguous: Iterator::Item, Add::Output. A generic parameter makes a trait family a type implements many times, like String's From<&str> and From<char>, costing annotations.
Common mistakes
- ✗Treating an associated type as mere shorthand for a generic parameter
- ✗Proposing
trait Iterator<T>, which would let one type iterate over several item types and need an annotation at every use - ✗Writing
Box<dyn Iterator>withoutItem = …, which fails with E0191
Follow-up questions
- →Why does
AddtakeRhsas a generic parameter butOutputas an associated type? - →How do you pin an associated type in a bound, as in
I: Iterator<Item = u32>?
MiddleTheoryOccasionalWhat is the orphan rule, and how does the wrapper pattern newtype bypass it?
What is the orphan rule, and how does the wrapper pattern newtype bypass it?
impl Trait for Type needs the trait or the type to be local to your crate, so impl Display for Vec<T> is E0117; this keeps one impl per pair across crates. A newtype struct Names(Vec<String>) is local at zero cost; a type alias is not.
Common mistakes
- ✗Trying to get around the rule with a
typealias, which is the same type and still gives E0117 - ✗Thinking the newtype wrapper costs memory or time, though its size equals its field's
- ✗Being unable to say why the rule exists: two crates could otherwise supply clashing impls
Follow-up questions
- →Why is
impl From<Celsius> for f64allowed when bothFromandf64are foreign? - →Why is implementing
Derefon a newtype just to inherit its methods discouraged?
MiddleTheoryOccasionalHow do std::ops traits map operators, and why implement Add for &T?
How do std::ops traits map operators, and why implement Add for &T?
a + b becomes Add::add(a, b). Rhs is a generic parameter, so Vec2 * f64 is its own impl; Output is associated, one result type per operand pair. add takes self by value, so add Add for &T when non-Copy operands must survive.
Common mistakes
- ✗Believing
addborrows its operands, then hitting E0382 aftera + bon a non-Copytype - ✗Thinking
Outputcould be a generic parameter without makinga + bambiguous - ✗Expecting
impl Mul<f64> for Vec2to also allow2.0 * v
Follow-up questions
- →Why can't
&&and||be overloaded the way+can? - →Why is
==defined byPartialEqfromstd::cmprather than by astd::opstrait?
SeniorTheoryOccasionalWhat makes a trait dyn-compatible, and how does where Self: Sized help?
What makes a trait dyn-compatible, and how does where Self: Sized help?
A trait is dyn-compatible (formerly object-safe) if each method fits one vtable entry: no generic methods, no Self return, no Sized supertrait. where Self: Sized drops an offending method from the vtable, leaving it for concrete types only.
Common mistakes
- ✗Believing a by-value
selfmethod breaks dyn compatibility, though it is allowed and only cannot be called throughdyn - ✗Expecting
Box<dyn Clone>to work, thoughClonerequiresSelf: Sizedand gives E0038 - ✗Thinking a method marked
where Self: Sizedcan still be called on a trait object
Follow-up questions
- →How does a
clone_box(&self) -> Box<dyn Shape>method stand in forCloneon trait objects? - →Why is a trait with an
async fnmethod not dyn-compatible, and what are the workarounds?