Loading...
Loading...
Master Rust macros - declarative and procedural macros
npx skill4agent add pluginagentmarketplace/custom-plugin-rust rust-macrosmacro_rules! vec_of_strings {
($($x:expr),* $(,)?) => {
vec![$($x.to_string()),*]
};
}
let v = vec_of_strings!["a", "b", "c"];| Specifier | Matches |
|---|---|
| Identifier |
| Expression |
| Type |
| Pattern |
| Token tree |
| Literal |
macro_rules! hashmap {
($($key:expr => $value:expr),* $(,)?) => {{
let mut map = std::collections::HashMap::new();
$(map.insert($key, $value);)*
map
}};
}
let m = hashmap! { "one" => 1, "two" => 2 };[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
quote! {
impl HelloMacro for #name {
fn hello() {
println!("Hello from {}!", stringify!(#name));
}
}
}.into()
}cargo expand # Expand all macros
cargo expand main # Expand specific| Problem | Solution |
|---|---|
| Hygiene issues | Use |
| Order matters | Define before use |