3 The compiler is capable of providing basic implementations for some traits via
4 the `#[derive]` [attribute][attribute]. These traits can still be
5 manually implemented if a more complex behavior is required.
7 The following is a list of derivable traits:
9 [`Eq`][eq], [`PartialEq`][partial-eq], [`Ord`][ord], [`PartialOrd`][partial-ord]
10 * [`Clone`][clone], to create `T` from `&T` via a copy.
11 * [`Copy`][copy], to give a type 'copy semantics' instead of 'move semantics'
12 * [`Hash`][hash], to compute a hash from `&T`.
13 * [`Default`][default], to create an empty instance of a data type.
14 * [`Debug`][debug], to format a value using the `{:?}` formatter.
17 // `Centimeters`, a tuple struct that can be compared
18 #[derive(PartialEq, PartialOrd)]
19 struct Centimeters(f64);
21 // `Inches`, a tuple struct that can be printed
26 fn to_centimeters(&self) -> Centimeters {
27 let &Inches(inches) = self;
29 Centimeters(inches as f64 * 2.54)
33 // `Seconds`, a tuple struct no additional attributes
37 let _one_second = Seconds(1);
39 // Error: `Seconds` can't be printed; it doesn't implement the `Debug` trait
40 //println!("One second looks like: {:?}", _one_second);
41 // TODO ^ Try uncommenting this line
43 // Error: `Seconds` can't be compared; it doesn't implement the `PartialEq` trait
44 //let _this_is_true = (_one_second == _one_second);
45 // TODO ^ Try uncommenting this line
47 let foot = Inches(12);
49 println!("One foot equals {:?}", foot);
51 let meter = Centimeters(100.0);
54 if foot.to_centimeters() < meter {
60 println!("One foot is {} than one meter.", cmp);
67 [attribute]: attribute.html
68 [eq]: https://doc.rust-lang.org/std/cmp/trait.Eq.html
69 [partial-eq]: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html
70 [ord]: https://doc.rust-lang.org/std/cmp/trait.Ord.html
71 [partial-ord]: https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html
72 [clone]: https://doc.rust-lang.org/std/clone/trait.Clone.html
73 [copy]: https://doc.rust-lang.org/core/marker/trait.Copy.html
74 [hash]: https://doc.rust-lang.org/std/hash/trait.Hash.html
75 [default]: https://doc.rust-lang.org/std/default/trait.Default.html
76 [debug]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
77 [derive]: https://doc.rust-lang.org/reference/attributes.html#derive