Sub topic 7
When a trait can be a trait object
This chapter assumes you know how to define and implement traits and have seen Box<dyn Trait> used for dynamic dispatch. Not every trait can be used behind dyn. A trait that can is called dyn compatible. Older material calls this "object safe".
Why some traits are rejected
A trait object is a pointer plus a vtable, which is a table of function pointers. The compiler builds the vtable from the trait's methods. For each method it must know one fixed function signature, and the concrete type has been erased. A method that needs the concrete type breaks that.
The main rules:
| Method or trait feature | Problem | Fix |
|---|---|---|
| Returns `Self` | The caller can't know the size of the erased type | Return `Box<dyn Trait>`, or add `where Self: Sized` |
| Generic type parameter on a method | A vtable can't hold one entry per possible `T` | Take `&dyn Other`, or add `where Self: Sized` |
| No `self` receiver (an associated function such as `new`) | There is no value to look up a vtable from | Add `where Self: Sized` |
| `Sized` as a supertrait (`Clone` has this) | Trait objects are unsized | Remove the supertrait |
| Associated constants | A vtable holds methods, not constants | Use a method instead |
Opting methods out with `where Self: Sized`
You can keep a trait dyn compatible and still have a few methods that need the concrete type. Mark those methods where Self: Sized. They are left out of the vtable, so they can't be called on a dyn Trait. They remain available on concrete types.
use std::fmt::Display;
trait Shape {
fn area(&self) -> f64;
fn scaled(&self, k: f64) -> Self
where
Self: Sized;
fn describe<T: Display>(&self, label: T) -> String
where
Self: Sized,
{
format!("{label}: {:.1}", self.area())
}
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
fn scaled(&self, k: f64) -> Square {
Square(self.0 * k)
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Square(2.0))];
println!("{}", shapes[0].area());
let big = Square(2.0).scaled(2.0);
println!("{}", big.describe("big"));
}shapes[0].area() works through the vtable. shapes[0].describe("x") would not compile, because describe is excluded from the trait object.
Checking the decision
The compiler applies these checks at the point where you write dyn Trait, not where you define the trait. A non-compatible trait compiles fine until you use it as an object.
Common errors
- Adding
#[derive(Clone)]-style bounds by writingtrait Shape: Clone. This makes the trait incompatible, becauseClonerequiresSized. If you need to clone boxed objects, add a method such asfn box_clone(&self) -> Box<dyn Shape>. - Adding a generic method to a published trait. This silently breaks every user who relies on
dyn Trait, unless you also addwhere Self: Sized. - Expecting
where Self: Sizedmethods to be callable onBox<dyn Trait>. They are not.
Exercise
A trait has fn new() -> Self; and fn name(&self) -> String;. Can you write Box<dyn MyTrait>? If not, what is the smallest change that makes it work, and what do you lose?
Show answer
No. new has no receiver and returns Self, so it can't go in a vtable. Change it to fn new() -> Self where Self: Sized;. The trait is then dyn compatible, and name works through Box<dyn MyTrait>. You lose the ability to call new on a trait object. You can still call it on concrete types, as in Concrete::new().