liveBook · Manning

Derive macro

As explained in Write Powerful Rust Macros

A Rust derive attribute requests compiler or procedural generation of trait implementations for a type.

A Rust derive attribute asks the compiler or a procedural macro to add functionality to a struct, enum, or union. The annotated type remains unchanged; generated functions or trait implementations are added alongside it. section 1.3.1

Use derive attributes when the generated behavior is repetitive, predictable, and easy to understand:

  • Add standard capabilities such as Debug, Clone, Default, or PartialEq with an annotation such as #[derive(Clone)]. section 1.3.2
  • Extend a type without modifying its definition or unrelated application code; derive macros are additive rather than transformative. section 1.3.1
  • Prefer derives over custom generation when the intent is immediately recognizable, because opaque or excessive generation can make code harder to understand. section 1.3.2

Building a custom Hello derive

Create a procedural-macro library and mark it with proc-macro = true. Define #[proc_macro_derive(Hello)] in lib.rs, then depend on that library from an application and write #[derive(Hello)] above a struct. A minimal setup uses Cargo, quote, syn, and a separate application crate; the macro can initially return an empty token stream before generating a Hello, World method. section 3.1

Figure 1.2 The types of macros in Rust
figure

Compare derive macros with attribute and function-like procedural macros through the macro taxonomy. section 1.3.1

How Write Powerful Rust Macros covers it

How deep it goes
Explains additive token generation and gives a procedural-macro project setup, but defers detailed macro implementation.
Examples
Uses Debug, Clone, Default, PartialEq, and a custom Hello derive backed by Cargo, quote, syn, and two Rust crates.
What you can do after
Build it from scratch as a procedural-macro library and apply a custom derive to an application type.
How it connects
Connects derive attributes with procedural macros, declarative macros, traits, structs, enums, unions, and attribute macros.

Also explained in

Compare how 5 books explain derive macro →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.