Sub topic 10
Building traits on other traits
What this chapter assumes
You should be able to define and implement a trait, write default methods, and constrain a generic function with a bound such as T: Display. You should also know what dyn Trait is at a basic level. This chapter covers how one trait can require another.
The working model: a supertrait is a requirement
A supertrait is a trait that another trait lists after a colon. In trait Named: Display, Display is the supertrait. The declaration means: a type can implement Named only if it already implements Display.
The relationship is a requirement, not inheritance. Named does not copy Display's methods or fields, and Display does not know Named exists. The compiler checks the requirement when you write impl Named for SomeType.
use std::fmt::{self, Display};
trait Named: Display {
fn shout(&self) -> String {
self.to_string().to_uppercase()
}
}
struct User(String);
struct Product(String);
impl Display for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Display for Product {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "product {}", self.0)
}
}
impl Named for User {}
impl Named for Product {}
fn announce(item: &impl Named) {
println!("{item} -> {}", item.shout());
}
fn main() {
announce(&User(String::from("ana")));
announce(&Product(String::from("lamp")));
}This prints ana -> ANA and product lamp -> PRODUCT LAMP.
Why the requirement is useful
The requirement gives you two things.
First, default methods can use the supertrait. shout calls self.to_string(), which exists because every Display type gets ToString. Without : Display, the compiler would reject this body, because it cannot assume Self implements Display.
Second, callers get the supertrait for free. announce only asks for impl Named, yet it uses {item} in println!, which needs Display. A bound on a trait implies bounds on all its supertraits. The longer form T: Named + Display is legal but redundant.
The requirement is checked at the impl site. If you write impl Named for Product and Product has no Display implementation, compilation fails with error E0277, saying that Product doesn't implement std::fmt::Display. The fix is to implement Display for Product. It is not to remove the supertrait.
Several supertraits
Join supertraits with +. The requirement is that all of them hold.
use std::fmt::Debug;
trait Entity: Debug + Clone {
fn id(&self) -> u32;
fn duplicate(&self) -> Self {
self.clone()
}
}
#[derive(Debug, Clone)]
struct Order {
id: u32,
}
impl Entity for Order {
fn id(&self) -> u32 {
self.id
}
}
fn log_copy<E: Entity>(e: &E) -> E {
let c = e.duplicate();
println!("copied {:?} with id {}", c, c.id());
c
}
fn main() {
let order = Order { id: 7 };
let _copy = log_copy(&order);
}This prints copied Order { id: 7 } with id 7. Here duplicate returns Self, which is only allowed because Clone implies Sized. That detail matters in the next section.
The relationships look like this:
Requirements chain. Entity also requires Sized, because Clone does. A bound E: Entity therefore gives you Debug, Clone, and Sized.
Supertraits and trait objects
A supertrait method can be called through a trait object. With Named: Display, a Box<dyn Named> can be printed with {}:
use std::fmt::{self, Display};
trait Named: Display {
fn shout(&self) -> String {
self.to_string().to_uppercase()
}
}
struct User(String);
struct Team(String);
impl Display for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Display for Team {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "team {}", self.0)
}
}
impl Named for User {}
impl Named for Team {}
fn main() {
let items: Vec<Box<dyn Named>> = vec![
Box::new(User(String::from("ana"))),
Box::new(Team(String::from("core"))),
];
for item in &items {
println!("{item} / {}", item.shout());
}
}Two gotchas apply to supertraits and dyn:
- A supertrait that requires
Sizedmakes the subtrait not dyn compatible.Entityabove cannot be used asdyn Entity, becauseClonerequiresSized. Debug is fine, butCloneis not. - Converting
&dyn Namedto&dyn Displayis called trait upcasting. It has been stable since Rust 1.86. On older compilers, you cannot do this conversion directly. Check your toolchain withrustc --versionbefore relying on it.
Choosing between a supertrait and other tools
| Situation | Tool | Reason |
|---|---|---|
| Every implementor of your trait must also have another capability, and your default methods use it | Supertrait | The requirement is stated once, at the trait. |
| Only one function needs two capabilities | Bound on the function, such as `T: Named + Clone` | Your trait stays small and does not impose the requirement on other users. |
| You want every type with trait A to get trait B automatically | Blanket implementation, `impl<T: A> B for T` | No manual `impl B` is needed. |
| You need `dyn` and the supertrait requires `Sized` | Redesign, or drop the supertrait | `Sized` supertraits rule out trait objects. |
The second row is the one people tend to miss. A supertrait is a permanent commitment. If you add : Clone to a public trait, every downstream implementor must implement Clone, and removing it later is a breaking change for callers who relied on it.
Common errors
- Implementing the subtrait without the supertrait. You get E0277 on the
implline. Implement or derive the supertrait first. ForDebugandClone,#[derive(Debug, Clone)]is enough. - Calling supertrait methods in a default method without declaring the supertrait. The body fails to compile, because
Selfhas no known methods beyond the trait's own. Add the supertrait. - Expecting the subtrait to be usable where the supertrait is required. A generic
T: Namedworks whereT: Displayis needed. The reverse does not hold. A plainDisplaytype is notNamed. - Method name clashes. If a subtrait and its supertrait both define
name, calls likex.name()are ambiguous when both traits are in scope. Disambiguate withNamed::name(&x)or<X as Named>::name(&x). Prefer distinct names to avoid this. - Cycles.
trait A: Bandtrait B: Ais an error. Requirements must form a directed graph without loops.
Summary of rules
trait Sub: Supermeans any type implementingSubmust implementSuper.- Default methods in
Subcan callSupermethods onself. - A bound on
Subimplies the bound onSuper. - Trait objects of
Subcan callSupermethods, as long asSubstays dyn compatible. Sizedin the chain removes dyn compatibility.
Exercise
You write trait Report: Debug { fn dump(&self) -> String { format!("{:?}", self) } } and then struct Log; impl Report for Log {} without deriving anything on Log. What happens, and what is the smallest fix?
Show answer
Compilation fails with E0277 because Log does not implement Debug, which Report requires. The smallest fix is to add #[derive(Debug)] above struct Log;.
Exercise
Why can Vec<Box<dyn Entity>> not be built when trait Entity: Debug + Clone, and which change would make it possible?
Show answer
Clone requires Sized, so Entity is not dyn compatible and cannot be used as a trait object. Removing Clone from the supertraits makes it possible. Move the cloning requirement into function bounds, such as fn log_copy<E: Entity + Clone>(e: &E), or drop duplicate. Keeping Debug is fine.
Exercise
A function has the signature fn show<T: Named>(x: &T) where trait Named: Display. Does the body need to add + Display to use println!("{x}")?
Show answer
No. The bound T: Named implies T: Display through the supertrait, so println!("{x}") compiles as written.