更多 trait

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. }

5. trait Pet: Animal {
6. fn name(&self) -> String;
7. }

9. struct Dog(String);

11. impl Animal for Dog {
12. fn leg_count(&self) -> u32 {
13. 4
14. }
15. }

17. impl Pet for Dog {
18. fn name(&self) -> String {
19. self.0.clone()
20. }
21. }

23. fn main() {
24. let puppy = Dog(String::from("Rex"));
25. println!("{} has {} legs", puppy.name(), puppy.leg_count());
26. }

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.