Sub topic 7
When a trait can be a trait object
This chapter assumes you know how to define and implement traits, how generics and trait bounds work, and what Box<dyn Trait> looks like. It covers the rules that decide whether dyn Trait is allowed. These rules are called dyn compatibility. Older documents call it object safety. You will also learn the standard workarounds when a trait breaks a rule.
Why the rules exist
A dyn Trait value is a pointer pair: one pointer to the data and one to a vtable. The vtable is a table of function pointers, one for each method of the trait. A call like shape.area() loads a pointer from the vtable and jumps to it.
The compiler builds that table without knowing the concrete type. So every method in it must have a single, fixed signature that works for any implementer. A method that needs the concrete type to be known cannot go in the table. Each dyn compatibility rule follows from this idea.
The rules
A trait is dyn compatible when all of the following hold.
| Rule | Why it matters |
|---|---|
| `Sized` is not a supertrait, and every supertrait is also dyn compatible. | `dyn Trait` is unsized, so it cannot implement a trait that requires `Sized`. `Clone` requires `Sized`, so `dyn Clone` is not allowed. |
| There are no associated constants. | A constant belongs to a type, not to a value, and a vtable is looked up through a value. |
| There are no associated types with generic parameters. | The compiler cannot fill in the type at the call site. |
| Every method is either dispatchable or opted out with `where Self: Sized`. | Methods that cannot be in the vtable must be removed from it explicitly. |
A method is dispatchable when it meets these conditions:
- It has a receiver of type
&self,&mut self,self: Box<Self>,self: Rc<Self>,self: Arc<Self>, orself: Pin<P>of one of those. - It has no type parameters. Lifetime parameters are fine.
- It does not mention
Selfanywhere except the receiver. That rules outfn merge(&self, other: Self)andfn duplicate(&self) -> Self. - It is not
asyncand does not returnimpl Trait.
A method with no receiver, such as fn new() -> Self, is an associated function. It cannot be dispatched, so it needs where Self: Sized.
If you use a trait that breaks a rule as dyn Trait, the compiler reports error E0038, "the trait cannot be made into an object". The message lists the offending method or item.
Opting methods out with `where Self: Sized`
You do not have to give up a whole trait because of one awkward method. Adding where Self: Sized removes that method from the vtable. The method still works on concrete types, but you cannot call it on a dyn Trait.
trait Animal {
fn name(&self) -> String;
// Needed to clone through a trait object (see below).
fn boxed_clone(&self) -> Box<dyn Animal>;
// Returns Self, so it cannot be in the vtable.
fn rename(&self, name: &str) -> Self
where
Self: Sized;
// Generic, so it cannot be in the vtable either.
fn describe_with<F: Fn(&str) -> String>(&self, f: F) -> String
where
Self: Sized,
{
f(&self.name())
}
}
#[derive(Clone)]
struct Dog {
name: String,
}
impl Animal for Dog {
fn name(&self) -> String {
self.name.clone()
}
fn boxed_clone(&self) -> Box<dyn Animal> {
Box::new(self.clone())
}
fn rename(&self, name: &str) -> Self {
Dog { name: name.to_string() }
}
}
impl Clone for Box<dyn Animal> {
fn clone(&self) -> Self {
self.boxed_clone()
}
}
fn main() {
let zoo: Vec<Box<dyn Animal>> = vec![Box::new(Dog { name: "Rex".to_string() })];
let copy = zoo.clone();
println!("{}", copy[0].name());
let dog = Dog { name: "Rex".to_string() };
let max = dog.rename("Max");
println!("{}", max.describe_with(|n| n.to_uppercase()));
}The program prints Rex and then MAX.
Animal is a valid trait object type even though rename and describe_with could never work through a vtable. Writing copy[0].rename("Z") would not compile, because that method is only available when the concrete type is known.
Cloning a trait object
Clone has a Sized supertrait, so Box<dyn Animal> cannot get a clone by making Animal: Clone. The example above shows the usual workaround, sometimes called the clone_box pattern:
- Add a dispatchable method, here
boxed_clone(&self) -> Box<dyn Animal>, that each implementer writes by cloning itself. - Implement
CloneforBox<dyn Animal>by calling that method.
The second step is allowed by the orphan rule. Box is marked fundamental, so Box<dyn Animal> counts as a local type when Animal is local.
The same idea applies to comparison and hashing. You cannot make PartialEq a supertrait of a trait you want as an object, because its rhs defaults to Self. Write a method such as fn equals(&self, other: &dyn Animal) -> bool and implement it yourself.
Associated types and generic traits
Associated types are allowed, but the trait object must say what they are. A dyn Iterator on its own is an error. You write dyn Iterator<Item = u32>.
fn evens(limit: u32) -> Box<dyn Iterator<Item = u32>> {
Box::new((0..limit).filter(|n| n % 2 == 0))
}
fn main() {
let v: Vec<u32> = evens(10).collect();
println!("{v:?}");
}The program prints [0, 2, 4, 6, 8]. The Item = u32 part is required because the vtable entry for next returns Option<Item>, and its layout depends on Item.
A generic trait works the same way. dyn Converter<String> and dyn Converter<i64> are two different types with two different vtables.
Calling collect on a Box<dyn Iterator> works because collect is declared with where Self: Sized, and Box<dyn Iterator> itself implements Iterator and is sized. The standard library uses this opt-out throughout Iterator.
Supertraits and default methods
A supertrait that is dyn compatible does not harm the subtrait. If trait Named: Display is dyn compatible, then dyn Named can call Display methods too. Since Rust 1.86 you can also convert &dyn Named to &dyn Display, which is called trait upcasting. Before that you needed a helper method such as fn as_display(&self) -> &dyn Display.
Default method bodies are ordinary members of the vtable. A default method that calls other trait methods through &self is fine. A default method that is generic or mentions Self needs where Self: Sized, as describe_with does above.
Choosing between generics and objects
Dyn compatibility is a design signal, not only an obstacle. Before reaching for workarounds, ask whether you need dyn at all.
- Use generics (
T: Traitorimpl Trait) when the concrete type is known at compile time. Traits withSelfin arguments, constructors, or generic methods are natural here. - Use
dyn Traitwhen you must store mixed types in one collection or hide the type behind a stable interface. Design the trait with small, receiver-based methods. - Consider an enum when you have a closed, known set of variants. It avoids both the vtable and the dyn compatibility rules.
A common pattern is to keep a small dyn-compatible core trait for objects, then put the extra methods in a second, generic extension trait with a blanket implementation. Iterator adapters work like this in many libraries.
Common mistakes
- Returning
Selffrom a method in a trait you later want as an object. ReturnBox<dyn Trait>or addwhere Self: Sized. - Adding
Clone,Default, orPartialEqas a supertrait. Each requiresSizedor usesSelfin its signature. - Using
async fnin a trait and then boxing it asdyn Trait. Return a boxed future by hand, or use a crate such asasync-trait. - Adding an associated constant to a trait that is already used as
dyn. This breaks every user of the trait object, so treat it as a breaking change.
Exercise
A trait Parser has the method fn parse(&self, input: &str) -> Self;. You want to use Vec<Box<dyn Parser>>. The compiler reports E0038. Give two ways to fix it.
Show answer
The method returns Self, so it cannot be in the vtable. First fix: change the return type to something that does not mention Self, such as Box<dyn Parser>, or a concrete type. Second fix: keep the signature and add where Self: Sized to the method. The method then works on concrete types but cannot be called on dyn Parser.
Exercise
Why does Box<dyn Iterator<Item = u32>> compile when plain Box<dyn Iterator> does not?
Show answer
The vtable entry for next returns Option<Self::Item>, and the compiler needs the concrete associated type to know the return layout. A trait object type must therefore name every associated type, as in Item = u32.