Sub topic 10
Building traits on other traits
This chapter assumes you can define and implement a trait, write default methods, and read a trait bound such as T: Display.
What a supertrait is
A supertrait is a trait that another trait requires. You write it after a colon in the trait definition:
trait Named: Display { /* ... */ }This says that any type implementing Named must also implement Display. Display is the supertrait and Named is the subtrait. The requirement is a promise about the implementing type. It is not inheritance, because Named gets no method bodies from Display.
Using the supertrait's methods
Because the compiler knows every Named type is also Display, the subtrait's default methods can call Display methods on self:
use std::fmt::{self, Display};
trait Named: Display {
fn shout(&self) -> String {
self.to_string().to_uppercase()
}
}
struct User(String);
impl Display for User {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl Named for User {}
fn announce(item: &impl Named) {
println!("{item}");
println!("{}", item.shout());
}
fn main() {
announce(&User(String::from("ana")));
}This prints ana and then ANA. Here shout calls to_string, which exists because of Display. The function announce also uses {item} formatting, although its bound names only Named. A bound on a subtrait implies bounds on all of its supertraits.
The order of implementation
You must implement the supertrait for the type as well as the subtrait. If you write impl Named for User {} and User has no Display implementation, compilation fails with an error that User doesn't implement Display. The two impl blocks can appear in any order in the file.
Several supertraits
Join supertraits with +:
trait Pet: Display + Clone {
fn name(&self) -> String {
self.to_string()
}
}Supertrait or plain bound?
A supertrait fits when the subtrait's own methods need the other behavior, or when the two always go together. If only some functions need both, a bound on those functions is more flexible: fn show<T: Display + Named>(x: &T). A supertrait forces every implementer of the subtrait to meet the requirement, so add one only when that is what you want.
Trait objects and upcasting
A &dyn Named can call Display methods, since Display is a supertrait. Since Rust 1.86, you can also coerce a &dyn Named to a &dyn Display. This is called trait upcasting. Older compilers reject that coercion.
Exercise
A trait is declared as trait Report: Debug { fn dump(&self) -> String { format!("{:?}", self) } }. Why does the default method compile, and what must a type do before it can implement Report?
Show answer
The default method compiles because Debug is a supertrait of Report, so the compiler knows self can be formatted with {:?}. A type must implement Debug (for example with #[derive(Debug)]) before it can implement Report.