How to Write an Attribute Macro in Rust

An attribute macro in Rust is a procedural macro that transforms an item based on a custom attribute, defined using the proc_macro crate.

An attribute macro in Rust is a procedural macro that transforms an item based on a custom attribute, defined using the proc_macro crate and the #[proc_macro_attribute] function.

use proc_macro::TokenStream;
use quote::quote;

#[proc_macro_attribute]
pub fn my_attr(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut item_tokens = item.clone();
    // Transform logic here
    item_tokens
}
  1. Create a new crate with proc-macro as the crate type in Cargo.toml.
  2. Add proc-macro = true to the [lib] section of Cargo.toml.
  3. Import TokenStream from proc_macro and quote from the quote crate.
  4. Define a function decorated with #[proc_macro_attribute] that takes the attribute tokens and the item tokens.
  5. Implement the transformation logic inside the function to modify the item tokens.
  6. Return the modified TokenStream from the function.