]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/trait/derive.md
New upstream version 1.25.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / trait / derive.md
1 # Derive
2
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.
6
7 The following is a list of derivable traits:
8 * Comparison 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.
15
16 ```rust,example
17 // `Centimeters`, a tuple struct that can be compared
18 #[derive(PartialEq, PartialOrd)]
19 struct Centimeters(f64);
20
21 // `Inches`, a tuple struct that can be printed
22 #[derive(Debug)]
23 struct Inches(i32);
24
25 impl Inches {
26 fn to_centimeters(&self) -> Centimeters {
27 let &Inches(inches) = self;
28
29 Centimeters(inches as f64 * 2.54)
30 }
31 }
32
33 // `Seconds`, a tuple struct no additional attributes
34 struct Seconds(i32);
35
36 fn main() {
37 let _one_second = Seconds(1);
38
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
42
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
46
47 let foot = Inches(12);
48
49 println!("One foot equals {:?}", foot);
50
51 let meter = Centimeters(100.0);
52
53 let cmp =
54 if foot.to_centimeters() < meter {
55 "smaller"
56 } else {
57 "bigger"
58 };
59
60 println!("One foot is {} than one meter.", cmp);
61 }
62 ```
63
64 ### See also:
65 [`derive`][derive]
66
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