Derive
The derive
attribute invokes one or more derive macros, allowing new items to be automatically generated for data structures. You can create derive
macros with procedural macros.
Example
The
PartialEq
derive macro emits an implementation ofPartialEq
forFoo<T> where T: PartialEq
. TheClone
derive macro does likewise forClone
.#![allow(unused)] fn main() { #[derive(PartialEq, Clone)] struct Foo<T> { a: i32, b: T, } }
The generated
impl
items are equivalent to:#![allow(unused)] fn main() { struct Foo<T> { a: i32, b: T } impl<T: PartialEq> PartialEq for Foo<T> { fn eq(&self, other: &Foo<T>) -> bool { self.a == other.a && self.b == other.b } } impl<T: Clone> Clone for Foo<T> { fn clone(&self) -> Self { Foo { a: self.a.clone(), b: self.b.clone() } } } }
The derive
attribute uses the MetaListPaths syntax to specify a list of paths to derive macros to invoke.
The derive
attribute may be applied to structs, enums, and unions.
The derive
attribute may be specified multiple times on an item, with all derive macros listed in all attributes being invoked.
The derive
attribute is exported in the standard library prelude as core::prelude::v1::derive
.
Built-in derives are defined in the language prelude. The list of built-in derives are:
The built-in derives include the automatically_derived
attribute on the implementations they generate.
During macro expansion, for each element in the list of derives, the corresponding derive macro expands to zero or more items.
The automatically_derived
attribute
The automatically_derived
attribute is used to annotate an implementation to indicate that it was automatically created by a derive macro. It has no direct effect, but it may be used by tools and diagnostic lints to detect these automatically generated implementations.
Example
Given
#[derive(Clone)]
onstruct Example
, the derive macro may produce:#![allow(unused)] fn main() { struct Example; #[automatically_derived] impl ::core::clone::Clone for Example { #[inline] fn clone(&self) -> Self { Example } } }
The automatically_derived
attribute uses the MetaWord syntax and so does not accept any arguments.
The automatically_derived
attribute may be placed on an implementation.
Note
rustc
currently accepts the attribute in other positions but lints against it.
Duplicate instances of the automatically_derived
attribute on the same implementation have no effect.
Note
rustc
lints against duplicate use of this attribute on uses following the first.
The automatically_derived
attribute has no behavior.