proc_macro_derive is a Rust attribute that marks a procedural macro function as a derive-macro entry point. Its parenthesized name, such as Hello, becomes the invocation name in #[derive(Hello)]; the function name is private to the implementation. section 3.2
A derive implementation follows a small interface:
- Accept a TokenStream containing the annotated item, such as a struct. section 3.2
- Return a TokenStream containing generated Rust code. section 3.2
- Use quote! to construct output and convert it with into(). section 3.2
Minimal derive entry point
With #[proc_macro_derive(Hello)] on pub fn hello(_item: TokenStream) -> TokenStream, a consumer can write #[derive(Hello)] on struct Example;. The generated tokens become part of the consumer's program, so invalid output produces a compiler error attributed to the Hello derive macro. section 3.2
use quote::quote;
use proc_macro::TokenStream;
#[proc_macro_derive(Hello)] #1
pub fn hello(_item: TokenStream) -> TokenStream {
let add_hello_world = quote! {}; #2
add_hello_world.into() #3
}
Inspect the compact implementation showing the attribute, TokenStream signature, quote! output, and conversion. section 3.2
