Default Methods

Traits can implement behavior in terms of other trait methods:

1. trait Equals {
2. fn equal(&self, other: &Self) -> bool;
3. fn not_equal(&self, other: &Self) -> bool {
4. !self.equal(other)
5. }
6. }

8. #[derive(Debug)]
9. struct Centimeter(i16);

11. impl Equals for Centimeter {
12. fn equal(&self, other: &Centimeter) -> bool {
13. self.0 == other.0
14. }
15. }

17. fn main() {
18. let a = Centimeter(10);
19. let b = Centimeter(20);
20. println!("{a:?} equals {b:?}: {}", a.equal(&b));
21. println!("{a:?} not_equals {b:?}: {}", a.not_equal(&b));
22. }