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
}
- Create a new crate with
proc-macroas the crate type inCargo.toml. - Add
proc-macro = trueto the[lib]section ofCargo.toml. - Import
TokenStreamfromproc_macroandquotefrom thequotecrate. - Define a function decorated with
#[proc_macro_attribute]that takes the attribute tokens and the item tokens. - Implement the transformation logic inside the function to modify the item tokens.
- Return the modified
TokenStreamfrom the function.