]>
Commit | Line | Data |
---|---|---|
532ac7d7 XL |
1 | # Derive |
2 | ||
3 | The *`derive` attribute* allows new [items] to be automatically generated for | |
4 | data structures. It uses the [_MetaListPaths_] syntax to specify a list of | |
5 | traits to implement or paths to [derive macros] to process. | |
6 | ||
7 | For example, the following will create an [`impl` item] for the | |
8 | [`PartialEq`] and [`Clone`] traits for `Foo`, and the type parameter `T` will be | |
9 | given the `PartialEq` or `Clone` constraints for the appropriate `impl`: | |
10 | ||
11 | ```rust | |
12 | #[derive(PartialEq, Clone)] | |
13 | struct Foo<T> { | |
14 | a: i32, | |
15 | b: T, | |
16 | } | |
17 | ``` | |
18 | ||
19 | The generated `impl` for `PartialEq` is equivalent to | |
20 | ||
21 | ```rust | |
22 | # struct Foo<T> { a: i32, b: T } | |
23 | impl<T: PartialEq> PartialEq for Foo<T> { | |
24 | fn eq(&self, other: &Foo<T>) -> bool { | |
25 | self.a == other.a && self.b == other.b | |
26 | } | |
27 | ||
28 | fn ne(&self, other: &Foo<T>) -> bool { | |
29 | self.a != other.a || self.b != other.b | |
30 | } | |
31 | } | |
32 | ``` | |
33 | ||
34 | You can implement `derive` for your own traits through [procedural macros]. | |
35 | ||
ba9703b0 XL |
36 | ## The `automatically_derived` attribute |
37 | ||
38 | The *`automatically_derived` attribute* is automatically added to | |
39 | [implementations] created by the `derive` attribute for built-in traits. It | |
40 | has no direct effect, but it may be used by tools and diagnostic lints to | |
41 | detect these automatically generated implementations. | |
42 | ||
416331ca XL |
43 | [_MetaListPaths_]: ../attributes.md#meta-item-attribute-syntax |
44 | [`Clone`]: ../../std/clone/trait.Clone.html | |
45 | [`PartialEq`]: ../../std/cmp/trait.PartialEq.html | |
46 | [`impl` item]: ../items/implementations.md | |
47 | [items]: ../items.md | |
48 | [derive macros]: ../procedural-macros.md#derive-macros | |
ba9703b0 XL |
49 | [implementations]: ../items/implementations.md |
50 | [items]: ../items.md | |
416331ca | 51 | [procedural macros]: ../procedural-macros.md#derive-macros |