Sub topic 14
Supertraits and Upcasting
This chapter assumes you can define traits and write Box<dyn Trait> values, and that you know a trait object is a fat pointer made of a data pointer and a vtable pointer. Here you will see how a trait that requires another trait behaves as a trait object, and when you can convert a dyn Sub into a dyn Super.
What a supertrait is
A supertrait is a trait that another trait requires. You write it after a colon in the trait declaration:
trait Named {
fn name(&self) -> String;
}
trait Animal: Named {
fn legs(&self) -> u32;
}Animal: Named means every type that implements Animal must also implement Named. The compiler checks this at each impl Animal for T. Inside Animal, default methods can call Named methods on self. You can list several supertraits with +, as in trait Animal: Named + Debug.
Supertraits express "is also". They are not inheritance in the object-oriented sense. Animal does not copy Named's methods. It only promises that they exist.
Supertrait methods on a trait object
A dyn Animal value can call every method of Animal and every method of its supertraits. The vtable for Animal has to carry the supertrait methods as well, because the caller only holds a pointer to the Animal vtable.
use std::fmt::Debug;
trait Named {
fn name(&self) -> String;
}
trait Animal: Named + Debug {
fn legs(&self) -> u32;
fn describe(&self) -> String {
format!("{} has {} legs", self.name(), self.legs())
}
}
#[derive(Debug)]
struct Dog;
#[derive(Debug)]
struct Bird;
impl Named for Dog {
fn name(&self) -> String {
String::from("dog")
}
}
impl Animal for Dog {
fn legs(&self) -> u32 {
4
}
}
impl Named for Bird {
fn name(&self) -> String {
String::from("bird")
}
}
impl Animal for Bird {
fn legs(&self) -> u32 {
2
}
}
fn main() {
let zoo: Vec<Box<dyn Animal>> = vec![Box::new(Dog), Box::new(Bird)];
for a in &zoo {
println!("{} / {:?}", a.describe(), a);
}
}This prints dog has 4 legs / Dog and bird has 2 legs / Bird.
Because Debug is a supertrait, dyn Animal itself implements Debug. That is why {:?} works on &Box<dyn Animal>. This is the standard way to make trait objects printable, cloneable through a helper method, comparable, and so on. Put the capability in the supertrait list and every trait object gets it.
Upcasting: from `dyn Animal` to `dyn Named`
Upcasting converts a trait object of a subtrait into a trait object of one of its supertraits. Before Rust 1.86 this was an error even though it is always safe. Since 1.86, trait upcasting coercion is stable and happens implicitly wherever a coercion is allowed.
trait Named {
fn name(&self) -> String;
}
trait Animal: Named {
fn legs(&self) -> u32;
}
struct Dog;
impl Named for Dog {
fn name(&self) -> String {
String::from("dog")
}
}
impl Animal for Dog {
fn legs(&self) -> u32 {
4
}
}
fn greet(n: &dyn Named) {
println!("hello, {}", n.name());
}
fn main() {
let a: Box<dyn Animal> = Box::new(Dog);
println!("legs: {}", a.legs());
// &dyn Animal coerces to &dyn Named.
greet(&*a);
// Box<dyn Animal> coerces to Box<dyn Named>.
let n: Box<dyn Named> = a;
println!("{}", n.name());
}The conversion works for the same pointer types that support trait objects: &dyn, &mut dyn, Box<dyn>, Rc<dyn>, and Arc<dyn>.
If your toolchain is older than 1.86, the compiler reports error E0308 (mismatched types) on the greet(&*a) line. The old workaround was a method such as fn as_named(&self) -> &dyn Named { self } written in every implementor. You can drop it on current compilers.
What happens inside the pointer
An upcast does not allocate, copy the value, or look at the concrete type. The data pointer stays the same. Only the second half of the fat pointer changes. The vtable for Animal records where the Named vtable for the same concrete type lives. The upcast reads that entry and writes it into the new fat pointer.
The diagram below shows that relationship.
The exact vtable layout is an implementation detail of the compiler and is not guaranteed. What the language does guarantee is the behavior: the upcast is cheap, and calls through the new pointer reach the same concrete implementation.
Which conversions are allowed
| Conversion | Allowed | Reason |
|---|---|---|
| `&dyn Animal` to `&dyn Named` | Yes | `Named` is a supertrait of `Animal`. |
| `Box<dyn Animal>` to `Box<dyn Named>` | Yes | Same rule, for an owning pointer. |
| `&dyn Animal` to `&dyn Any` when `Animal: Any` | Yes | `Any` is a supertrait. |
| `dyn Job + Send` to `dyn Job` | Yes | Dropping an auto trait only removes a promise. |
| `dyn Job` to `dyn Job + Send` | No | The compiler cannot know the concrete type is `Send`. |
| `&dyn Named` to `&dyn Animal` | No | That is downcasting, which needs the concrete type. |
| `&dyn Animal` to `&dyn Other` for an unrelated trait | No | `Other` is not in the supertrait list. |
The rule of thumb: you can go to anything the trait object already promises, and never to something it does not.
Upcasting to `dyn Any`
The most common use of upcasting is recovering the concrete type. Any requires 'static, so a trait that has Any as a supertrait only describes 'static types. The upcast then gives you a &dyn Any to downcast. The next chapter covers downcast_ref in more detail. Here is the short form without helper methods:
use std::any::Any;
trait Component: Any {
fn update(&mut self);
}
struct Health(u32);
impl Component for Health {
fn update(&mut self) {
self.0 -= 1;
}
}
fn main() {
let mut c: Box<dyn Component> = Box::new(Health(10));
c.update();
let any: &dyn Any = &*c;
if let Some(h) = any.downcast_ref::<Health>() {
println!("health = {}", h.0);
}
}This prints health = 9. Compare it with the as_any method in the earlier example. That method was the only option before upcasting was stable, and every implementor had to repeat it.
The extra reference mistake
Be careful about how you borrow. &*c is a &dyn Component, which upcasts to &dyn Any. But &c is a &Box<dyn Component>. A Box<dyn Component> is itself a sized 'static type, so it also coerces to &dyn Any, and it does so without any error. The Any value then describes Box<dyn Component>, not Health. The downcast to Health returns None, and nothing warns you. When a downcast fails unexpectedly, check that you dereferenced the box first.
Supertraits and dyn compatibility
A subtrait is dyn compatible only if its supertraits are too. These cases break it:
trait Animal: Sized. Adyn Animalis unsized, so it cannot satisfySized. The trait can never be a trait object.- A supertrait with a method that fails the dyn compatibility rules and has no
where Self: Sizedopt-out. Examples are a generic method, or a method that returnsSelf. The subtrait inherits the problem. - A supertrait that mentions
Selfas a type parameter, such astrait Animal: PartialEq<Self>.PartialEqwithout arguments (PartialEq<Self>by default) is the typical case. Adyn Animalcould not know the concrete type to compare with.
Two supertraits worth remembering are Clone, which requires Sized and so makes your trait not dyn compatible, and Debug, which is dyn compatible and safe to use. For cloning trait objects, write a method such as fn box_clone(&self) -> Box<dyn Animal> and keep Clone out of the supertrait list.
Common errors
- Using upcasting on an old toolchain. Check
rustc --version. Below 1.86, the coercion fails with a mismatched types error. - Expecting a downcast to a subtrait.
&dyn Namedcannot become&dyn Animal. If you need that, store the concrete type or useAny. - Adding
Sizedas a supertrait to "fix" a generic method. This removes the whole trait from trait-object use. Putwhere Self: Sizedon the one method instead. - Forgetting
'static.trait Component: Anyrejects types that borrow data. This is by design, becauseAnyonly works with'statictypes.
Exercise
A trait is declared as trait Widget: Any { }. You have w: Box<dyn Widget> that holds a Button. You write let any: &dyn Any = &w; and then call any.downcast_ref::<Button>(). What does it return, and how do you fix it?
Show answer
It returns None. The expression &w is a &Box<dyn Widget>, so the Any value describes the box type, not Button. Write let any: &dyn Any = &*w; instead. That upcasts the &dyn Widget to &dyn Any, and the downcast then succeeds.
Exercise
Given trait Animal: Named, which of these compile on Rust 1.86 or later: (a) let n: &dyn Named = animal_ref; where animal_ref: &dyn Animal, (b) let a: &dyn Animal = named_ref; where named_ref: &dyn Named?
Show answer
Only (a) compiles. It is an upcast to a supertrait. (b) is a downcast, which the compiler cannot do because it does not know whether the concrete type implements Animal.