Create a procedural macro crate with the `proc_macro_derive` attribute to automatically generate code for your types.
You write a derive macro by creating a procedural macro crate that implements the proc_macro API to parse and transform Rust tokens.
use proc_macro::TokenStream;
#[proc_macro_derive(MyDerive)]
pub fn my_derive(input: TokenStream) -> TokenStream {
// Parse input and generate expanded code here
input
}
In your Cargo.toml, set proc-macro = true in the [lib] section and name the crate with a proc-macro suffix.
A derive macro is a tool that automatically generates boilerplate code for your custom data structures when you add a specific attribute to them. Think of it as a template that fills in the repetitive parts of your code so you don't have to write them manually every time. You use this when you need your structs or enums to automatically support features like printing, cloning, or comparing values.