Derive

The compiler is capable of providing basic implementations for some traits via
the #[derive] attribute. These traits can still be
manually implemented if a more complex behavior is required.

The following is a list of derivable traits:

  • Comparison traits:
    Eq, PartialEq, Ord, PartialOrd
  • Clone, to create T from &T via a copy.
  • Copy, to give a type ‘copy semantics’ instead of ‘move semantics’
  • Hash, to compute a hash from &T.
  • Default, to create an empty instance of a data type.
  • Debug, to format a value using the {:?} formatter.
  1. // `Centimeters`, a tuple struct that can be compared
  2. #[derive(PartialEq, PartialOrd)]
  3. struct Centimeters(f64);
  4. // `Inches`, a tuple struct that can be printed
  5. #[derive(Debug)]
  6. struct Inches(i32);
  7. impl Inches {
  8. fn to_centimeters(&self) -> Centimeters {
  9. let &Inches(inches) = self;
  10. Centimeters(inches as f64 * 2.54)
  11. }
  12. }
  13. // `Seconds`, a tuple struct no additional attributes
  14. struct Seconds(i32);
  15. fn main() {
  16. let _one_second = Seconds(1);
  17. // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait
  18. //println!("One second looks like: {:?}", _one_second);
  19. // TODO ^ Try uncommenting this line
  20. // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait
  21. //let _this_is_true = (_one_second == _one_second);
  22. // TODO ^ Try uncommenting this line
  23. let foot = Inches(12);
  24. println!("One foot equals {:?}", foot);
  25. let meter = Centimeters(100.0);
  26. let cmp =
  27. if foot.to_centimeters() < meter {
  28. "smaller"
  29. } else {
  30. "bigger"
  31. };
  32. println!("One foot is {} than one meter.", cmp);
  33. }

See also:

derive