]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/attributes/derive.md
New upstream version 1.66.0+dfsg1
[rustc.git] / src / doc / reference / src / attributes / derive.md
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 ```
29
30 You can implement `derive` for your own traits through [procedural macros].
31
32 ## The `automatically_derived` attribute
33
34 The *`automatically_derived` attribute* is automatically added to
35 [implementations] created by the `derive` attribute for built-in traits. It
36 has no direct effect, but it may be used by tools and diagnostic lints to
37 detect these automatically generated implementations.
38
39 [_MetaListPaths_]: ../attributes.md#meta-item-attribute-syntax
40 [`Clone`]: ../../std/clone/trait.Clone.html
41 [`PartialEq`]: ../../std/cmp/trait.PartialEq.html
42 [`impl` item]: ../items/implementations.md
43 [items]: ../items.md
44 [derive macros]: ../procedural-macros.md#derive-macros
45 [implementations]: ../items/implementations.md
46 [items]: ../items.md
47 [procedural macros]: ../procedural-macros.md#derive-macros