Sub topic 10
Which Traits Can Be Trait Objects
This chapter assumes you know how to define and implement traits, how Box<dyn Trait> and &dyn Trait are used, and what a vtable is. Here you learn the rules that decide whether dyn Trait is allowed for a given trait. You also learn how to read the compiler's complaints and fix them.
Dyn compatibility in one idea
A trait object erases the concrete type. After erasure the compiler knows only the vtable, so every method in the vtable must be callable without knowing Self. A trait is dyn compatible (formerly called object safe) when every method can be called that way. Older books and error messages may still say "object safety". The rules are the same.
A trait that is not dyn compatible still works fine with generics. The restriction applies only to writing dyn Trait.
The rules
The Rust reference lists these requirements for a trait to be usable as dyn Trait:
| Rule | Why it exists |
|---|---|
| `Sized` must not be a supertrait | `dyn Trait` is unsized, so it could never implement the trait |
| All supertraits must be dyn compatible | The supertrait methods also go through the vtable |
| No associated constants | A constant has no receiver to find a vtable through |
| No generic associated types | The vtable cannot hold one entry per type argument |
| Every method must be dispatchable, or opted out with `where Self: Sized` | See the next section |
A dispatchable method meets all of these conditions:
- It has no type parameters. Lifetime parameters are fine.
- It does not mention
Selfexcept as the receiver. - Its receiver is
&self,&mut self,self: Box<Self>,self: Rc<Self>,self: Arc<Self>, orself: Pin<P>of one of those pointers. - It does not return an opaque type, so no
-> impl Traitand noasync fn.
An associated function with no receiver, such as fn new() -> Self, is also not dispatchable. There is no value to read a vtable from.
A compatible trait with several method shapes
This trait uses several allowed shapes. It has a &mut self method, a Box<Self> receiver, and a method with a lifetime parameter.
trait Animal {
fn name(&self) -> String;
fn rename(&mut self, new_name: &str);
fn into_name(self: Box<Self>) -> String;
fn describe<'a>(&self, prefix: &'a str) -> String {
format!("{}{}", prefix, self.name())
}
}
struct Dog {
name: String,
}
impl Animal for Dog {
fn name(&self) -> String {
self.name.clone()
}
fn rename(&mut self, new_name: &str) {
self.name = new_name.to_string();
}
fn into_name(self: Box<Self>) -> String {
self.name
}
}
fn main() {
let mut pet: Box<dyn Animal> = Box::new(Dog { name: "Rex".to_string() });
pet.rename("Max");
println!("{}", pet.describe("dog: "));
println!("{}", pet.into_name());
}This prints dog: Max and then Max. The self: Box<Self> receiver is what lets into_name consume a boxed trait object. Without it, a method taking self by value could not be called on dyn Animal.
What breaks the rules
Each of these four signatures makes a trait not dyn compatible:
fn new() -> Self;has no receiver.fn duplicate(&self) -> Self;returnsSelf. The caller would need to know the size of the result.fn same(&self, other: &Self) -> bool;usesSelfin an argument. Twodynvalues might hide different concrete types.fn map<T>(&self, t: T);is generic. One vtable slot cannot cover everyT.
The same applies to supertraits. trait Cloneable: Clone fails because Clone requires Sized and returns Self. PartialEq also fails, because its right-hand side type defaults to Self.
The compiler reports these cases with error E0038 and a note listing each violation, for example "...because method duplicate references the Self type in its return type". Read that note first. It names the exact method and the exact rule.
Opting a method out with `where Self: Sized`
Often you want the method for concrete types and have no need to call it through dyn. Add where Self: Sized to that method. The compiler leaves it out of the vtable and stops counting it against dyn compatibility.
trait Widget {
fn label(&self) -> String;
fn new(label: &str) -> Self
where
Self: Sized;
fn with_suffix(&self, suffix: &str) -> Self
where
Self: Sized,
{
Self::new(&format!("{}{}", self.label(), suffix))
}
fn boxed_clone(&self) -> Box<dyn Widget>;
}
struct Button(String);
impl Widget for Button {
fn label(&self) -> String {
self.0.clone()
}
fn new(label: &str) -> Self {
Button(label.to_string())
}
fn boxed_clone(&self) -> Box<dyn Widget> {
Box::new(Button(self.0.clone()))
}
}
fn main() {
let b = Button::new("ok");
let c = b.with_suffix("!");
let w: Box<dyn Widget> = Box::new(c);
let w2 = w.boxed_clone();
println!("{} {}", w.label(), w2.label());
}This prints ok! ok!. Three things are worth noting:
newandwith_suffixwork onButton, becauseButtonisSized.- Neither method can be called on
dyn Widget. The compiler rejectsw.with_suffix("?")with an error saying the method has aSelf: Sizedbound. boxed_cloneis the usual workaround for cloning a trait object. It returnsBox<dyn Widget>instead ofSelf, so it is dispatchable.
Associated types must be named
Associated types are allowed, but the trait object type has to say what they are. The compiler cannot build a vtable for next_item without knowing the return type.
trait Source {
type Item;
fn next_item(&mut self) -> Option<Self::Item>;
}
struct Counter(u32);
impl Source for Counter {
type Item = u32;
fn next_item(&mut self) -> Option<u32> {
if self.0 < 3 {
self.0 += 1;
Some(self.0)
} else {
None
}
}
}
fn drain(s: &mut dyn Source<Item = u32>) -> u32 {
let mut total = 0;
while let Some(x) = s.next_item() {
total += x;
}
total
}
fn main() {
println!("{}", drain(&mut Counter(0)));
}This prints 6. Writing &mut dyn Source without Item = u32 is error E0191, "the value of the associated type Item must be specified". The standard library's dyn Iterator<Item = T> follows the same pattern.
A consequence is that two trait objects with different Item types are different types. You cannot put Box<dyn Source<Item = u32>> and Box<dyn Source<Item = String>> in the same Vec.
Choosing a fix
When the compiler rejects dyn Trait, pick the smallest change that keeps your design:
- Method is only useful on concrete types. Add
where Self: Sizedto that method. - Method returns
Selfto copy or build a value. ReturnBox<dyn Trait>instead, as inboxed_clone. - Method has a type parameter. Replace it with a
&dyn OtherorBox<dyn Other>argument if the callers can accept that. Otherwise keep it generic and addwhere Self: Sized. - Method uses
async fnor returnsimpl Trait. Return a boxed value, such asBox<dyn Future<Output = T> + '_>orBox<dyn Iterator<Item = T> + '_>. Or putwhere Self: Sizedon the method ifdyncallers don't need it. - Trait has an associated const. Move the value into a method such as
fn id(&self) -> u32. - None of the above fit. Use generics for this trait and keep
dynfor a smaller companion trait that holds only the methods you need at runtime.
Exercises
Exercise
The trait below does not compile as Box<dyn Report>. Name the two violations and give a fix for each that keeps dyn Report usable.
trait Report {
fn title(&self) -> String;
fn empty() -> Self;
fn convert<T: From<String>>(&self) -> T;
}
Show answer
empty has no receiver, and convert has a type parameter. Neither can be put in a vtable. Fix both by adding where Self: Sized to empty and to convert. The compiler then leaves them out of the vtable, and title is the only method callable on dyn Report. Concrete types still have all three methods.
Exercise
Why does fn same(&self, other: &Self) -> bool break dyn compatibility, and why does adding where Self: Sized fix it?
Show answer
Through &dyn Trait the compiler knows nothing about the concrete type, so it cannot check that other has the same concrete type as self. A vtable entry cannot describe an argument whose type is Self. With where Self: Sized the method is excluded from the vtable, so the trait stays dyn compatible and the method remains callable on concrete types.