]> git.proxmox.com Git - rustc.git/blame - src/doc/reference/src/attributes/derive.md
New upstream version 1.44.1+dfsg1
[rustc.git] / src / doc / reference / src / attributes / derive.md
CommitLineData
532ac7d7
XL
1# Derive
2
3The *`derive` attribute* allows new [items] to be automatically generated for
4data structures. It uses the [_MetaListPaths_] syntax to specify a list of
5traits to implement or paths to [derive macros] to process.
6
7For example, the following will create an [`impl` item] for the
8[`PartialEq`] and [`Clone`] traits for `Foo`, and the type parameter `T` will be
9given the `PartialEq` or `Clone` constraints for the appropriate `impl`:
10
11```rust
12#[derive(PartialEq, Clone)]
13struct Foo<T> {
14 a: i32,
15 b: T,
16}
17```
18
19The generated `impl` for `PartialEq` is equivalent to
20
21```rust
22# struct Foo<T> { a: i32, b: T }
23impl<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
34You can implement `derive` for your own traits through [procedural macros].
35
ba9703b0
XL
36## The `automatically_derived` attribute
37
38The *`automatically_derived` attribute* is automatically added to
39[implementations] created by the `derive` attribute for built-in traits. It
40has no direct effect, but it may be used by tools and diagnostic lints to
41detect 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