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. }
  7. #[derive(Debug)]
  8. struct Centimeter(i16);
  9. impl Equals for Centimeter {
  10. fn equal(&self, other: &Centimeter) -> bool {
  11. self.0 == other.0
  12. }
  13. }
  14. fn main() {
  15. let a = Centimeter(10);
  16. let b = Centimeter(20);
  17. println!("{a:?} equals {b:?}: {}", a.equal(&b));
  18. println!("{a:?} not_equals {b:?}: {}", a.not_equal(&b));
  19. }