Supertraits

A trait can require that types implementing it also implement other traits, called supertraits. Here, any type implementing Pet must implement Animal.

  1. trait Animal {
  2.     fn leg_count(&self) -> u32;
  3. }
  4. trait Pet: Animal {
  5.     fn name(&self) -> String;
  6. }
  7. struct Dog(String);
  8. impl Animal for Dog {
  9.     fn leg_count(&self) -> u32 {
  10.         4
  11.     }
  12. }
  13. impl Pet for Dog {
  14.     fn name(&self) -> String {
  15.         self.0.clone()
  16.     }
  17. }
  18. fn main() {
  19.     let puppy = Dog(String::from("Rex"));
  20.     println!("{} has {} legs", puppy.name(), puppy.leg_count());
  21. }

This is sometimes called “trait inheritance” but students should not expect this to behave like OO inheritance. It just specifies an additional requirement on implementations of a trait.