Sub topic 10
Which traits can be trait objects
This chapter assumes you can write traits and generics, and that you have seen Box<dyn Trait> and know that method calls on it go through a vtable. Here you will learn which traits the compiler accepts behind dyn. This property is called dyn compatibility. Older material calls it object safety.
Why some traits are rejected
A vtable holds one function pointer per method. The compiler builds it once for each concrete type, and it must know each method's exact signature. Once the concrete type is erased behind dyn Trait, anything that depends on that type or on a generic parameter can no longer be resolved. The compiler rejects the trait to prevent that.
The rules
A trait is dyn compatible when all of these hold:
| Rule | Why it is needed |
|---|---|
| No `Self: Sized` supertrait | `dyn Trait` is unsized, so it could never implement the trait. |
| Every supertrait is dyn compatible | The vtable includes supertrait methods. |
| No associated constants | A constant has no single value without a concrete type. |
| No methods that return `Self` or take `Self` as an argument | The caller does not know the concrete type. |
| No generic type parameters on methods | One vtable slot cannot hold unlimited monomorphized copies. |
| No associated functions without a receiver | There is no value to read a vtable from. |
| Receiver is `&self`, `&mut self`, `Box<Self>`, `Rc<Self>`, `Arc<Self>`, or `Pin` of one of these | The receiver must be a pointer the vtable can be reached through. |
Associated types are allowed, but you must name them in the object type, as in dyn Iterator<Item = u32>.
A common failure: cloning
Clone requires Sized, so trait Animal: Clone cannot be a trait object. A method returning Self fails for the same reason. The usual fix is a method that returns a box.
trait Animal {
fn name(&self) -> String;
fn boxed_clone(&self) -> Box<dyn Animal>;
}
// This trait is not dyn compatible: `duplicate` returns Self.
#[allow(dead_code)]
trait Bad {
fn duplicate(&self) -> Self;
}
// let x: Box<dyn Bad>; // error: the trait `Bad` is not dyn compatible
#[derive(Clone)]
struct Dog;
impl Animal for Dog {
fn name(&self) -> String {
String::from("dog")
}
fn boxed_clone(&self) -> Box<dyn Animal> {
Box::new(self.clone())
}
}
fn main() {
let a: Box<dyn Animal> = Box::new(Dog);
let b = a.boxed_clone();
println!("{} {}", a.name(), b.name());
}boxed_clone returns Box<dyn Animal>, a type whose size is known and which does not mention the concrete type. This program prints dog dog.
Checking a trait
Walk through the rules in this order to find the blocker.
The where Self: Sized branch is covered in the next chapter. It lets you keep a few non-compatible methods without losing dyn support for the whole trait.
Reading the error
When you write dyn Bad, the compiler reports "the trait Bad is not dyn compatible" and then lists each violating item. Each note points at one method or supertrait. Fix the items on the list, or stop using dyn and use a generic function instead.
Common mistakes
- Adding
: Cloneor: Sizedto a trait and then usingdyn Traitelsewhere in the program. - Writing a generic method such as
fn visit<V: Visitor>(&self, v: V)on a trait that must be boxed. Taking&mut dyn Visitorinstead removes the generic parameter. - Forgetting to name associated types, which gives an error such as "the value of the associated type
Itemmust be specified".
Exercise
The trait trait Shape { fn scale(&self, k: f64) -> Self; } is not dyn compatible. Rewrite scale so Box<dyn Shape> becomes legal and callers can still scale a shape.
Show answer
Return a boxed trait object instead of Self: fn scale(&self, k: f64) -> Box<dyn Shape>;. The return type no longer depends on the concrete type, so the vtable slot has a fixed signature. This is the same technique as boxed_clone above.