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 createTfrom&Tvia 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);
5. // `Inches`, a tuple struct that can be printed
6. #[derive(Debug)]
7. struct Inches(i32);
9. impl Inches {
10. fn to_centimeters(&self) -> Centimeters {
11. let &Inches(inches) = self;
13. Centimeters(inches as f64 * 2.54)
14. }
15. }
17. // `Seconds`, a tuple struct no additional attributes
18. struct Seconds(i32);
20. fn main() {
21. let _one_second = Seconds(1);
23. // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait
24. //println!("One second looks like: {:?}", _one_second);
25. // TODO ^ Try uncommenting this line
27. // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait
28. //let _this_is_true = (_one_second == _one_second);
29. // TODO ^ Try uncommenting this line
31. let foot = Inches(12);
33. println!("One foot equals {:?}", foot);
35. let meter = Centimeters(100.0);
37. let cmp =
38. if foot.to_centimeters() < meter {
39. "smaller"
40. } else {
41. "bigger"
42. };
44. println!("One foot is {} than one meter.", cmp);
45. }
