Rust Reference ยท Attributes
The #[derive] attribute
Reference for Rust #[derive]: which standard traits can be derived, the bounds it adds to generics, derive order rules, and when to write impls by hand.
#[derive(...)] asks the compiler to write a trait implementation for a struct, enum or union. You list the traits, and the compiler generates an impl that works field by field (or variant by variant). It is the fastest way to give a type Debug printing, copying, comparison, hashing or a default value.
The standard library lets you derive Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash and Default. Libraries can add more through procedural macros (for example serde's Serialize).
#[derive(Debug, Clone, PartialEq)] struct Point { x: i32, y: i32 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
#[derive(Trait1, Trait2, ...)] struct / enum / union Name<generics> { ... }
| Derivable trait | What the generated code does |
|---|---|
Debug |
Prints the type name and fields in {:?} and {:#?} form |
Clone |
Clones every field; for enums, clones the active variant |
Copy |
Marker; requires every field to be Copy and the type to be Clone |
PartialEq, Eq |
Field-wise equality; Eq is a marker meaning equality is total |
PartialOrd, Ord |
Lexicographic by field order; enums compare by variant order first |
Hash |
Hashes fields in order, consistent with the derived PartialEq |
Default |
Calls Default::default() on each field; enums need one #[default] unit variant |
Errors and edge cases:
- Every field type must implement the derived trait, or the derive fails to compile.
CopyrequiresCloneas well: derive both.Eqcannot be derived when a field isf32orf64, because floats are notEq.- Deriving
Defaulton an enum without a#[default]variant is an error.
Usage notes
- Generic bounds. For
struct Wrapper<T>,#[derive(Clone)]generatesimpl<T: Clone> Clone for Wrapper<T>. The bound is on every type parameter, even if a parameter appears only behind a reference, which sometimes is stricter than needed; write the impl by hand in that case. - Field order matters for
PartialOrd,OrdandHashconsistency. Reordering fields changes ordering results. - Keep derives consistent. If you hand-write
PartialEq, also hand-writeHashso that equal values hash equally. Mixing a manual one with a derived one is a common bug source. - Debug output is not a stable format. Do not parse it; use
Displayor a serialization crate for output other code reads. Copyis a promise. It makes every assignment a bit copy, so only derive it for small, plain data types.- Derive does not run on a type alias or trait; it attaches to the definition of the type itself.
#[derive(Default)]on enums with#[default]has been available since Rust 1.62.
Related
Debug,Copy,Default,PartialEqandEq,Hash- Lessons: Copy and Clone, Traits, Structs