过程宏基础
过程宏类型
┌─────────────────────────────────────────────────────┐
│ 过程宏类型 │
├─────────────────────────────────────────────────────┤
│ │
│ #[derive] 派生宏 │
│ #[derive(MyTrait)] │
│ 为结构体/枚举自动生成代码 │
│ │
│ #[attribute] 属性宏 │
│ #[route(GET, "/users")] │
│ 修改被标注项的行为 │
│ │
│ function! 函数宏 │
│ sql!(SELECT * FROM users) │
│ 类似 macro_rules!,但功能更强 │
│ │
└─────────────────────────────────────────────────────┘创建派生宏
rust
▶ Run// Cargo.toml (proc-macro crate)
[lib]
proc-macro = true
[dependencies]
syn = "2.0"
quote = "1.0"
proc-macro2 = "1.0"rust
▶ Run// lib.rs
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
// 解析输入
let ast = parse_macro_input!(input as DeriveInput);
let name = &ast.ident;
// 生成代码
let gen = quote! {
impl HelloMacro for #name {
fn hello_macro() {
println!("Hello! My name is {}!", stringify!(#name));
}
}
};
gen.into()
}使用派生宏
rust
▶ Run// 主 crate
use my_macro_crate::HelloMacro;
trait HelloMacro {
fn hello_macro();
}
#[derive(HelloMacro)]
struct Person;
fn main() {
Person::hello_macro(); // Hello! My name is Person!
}