Sub topic 14
Supertraits and Upcasting
This chapter assumes you can write traits, build Box<dyn Trait> values, and know what a vtable is. It covers how a trait that requires another trait behaves as a trait object, and how to convert between the two.
Supertraits
A supertrait is a trait that another trait requires. Writing trait Animal: Named means any type implementing Animal must also implement Named.
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 describe(a: &dyn Animal) {
// name() comes from the supertrait, but is callable on dyn Animal.
println!("{} has {} legs", a.name(), a.legs());
}
fn main() {
let a: Box<dyn Animal> = Box::new(Dog);
describe(&*a);
}The vtable for dyn Animal includes the methods of Animal and of every supertrait. That is why a.name() works without extra steps.
Upcasting
Upcasting converts a dyn Animal into a dyn Named, the supertrait object. Since Rust 1.86 this is a built-in coercion that works behind any pointer type that supports unsizing.
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 show_name(n: &dyn Named) {
println!("{}", n.name());
}
fn main() {
let boxed: Box<dyn Animal> = Box::new(Dog);
let r: &dyn Named = &*boxed; // reference upcast
show_name(r);
let owned: Box<dyn Named> = boxed; // Box upcast, moves the box
show_name(&*owned);
}Internally, the compiler builds the vtable for dyn Named from the vtable of dyn Animal. The data pointer stays the same, and only the vtable pointer changes.
Upcasting on older compilers
Before Rust 1.86, the lines above fail with a type mismatch error. The usual workaround is a method that does the conversion manually:
trait Animal: Named {
fn legs(&self) -> u32;
fn as_named(&self) -> &dyn Named;
}Each implementor writes fn as_named(&self) -> &dyn Named { self }. If you must support an older toolchain, check your minimum supported Rust version before relying on the coercion.
Common errors
- Upcasting is one-way. You cannot turn a
&dyn Namedback into a&dyn Animalwith a coercion. Recovering a subtrait or concrete type needsdyn Any, covered in the next chapter. - The supertrait must be dyn compatible too. If
Namedhad a generic method withoutwhere Self: Sized,dyn Animalwould not be allowed. - A
Sizedsupertrait blocks trait objects.trait Animal: Sizedmakesdyn Animalimpossible, because trait objects are unsized. - Supertrait methods are not inherent. Calling
a.name()requires theNamedtrait to be in scope when it is defined in another module.
Why this matters
Supertraits let you build layered interfaces. Code that only needs naming accepts &dyn Named. Code that needs more accepts &dyn Animal. Upcasting lets one stored Box<dyn Animal> serve both kinds of caller without a wrapper method.
Exercise
Given let a: Box<dyn Animal> = Box::new(Dog); where trait Animal: Named, write the line that produces a &dyn Named from a. Then say why the reverse conversion, from &dyn Named to &dyn Animal, does not compile.
Show answer
Use let n: &dyn Named = &*a;. The reverse fails because a dyn Named vtable has no information about whether the concrete type also implements Animal. Many types implement Named without implementing Animal, so the compiler cannot allow the conversion. To recover that information at runtime you need dyn Any and downcast_ref to the concrete type.