如何使用Rust宏同时为多个条目应用多个属性
Rust宏实现批量为多个条目添加属性
直接上可运行的宏实现:
macro_rules! apply_my_attributes { ( ($(#[$attr:meta]),+) $( $item:item )+ ) => { $( $(#[$attr])* $item )+ }; }
工作原理
- 外层的
$( ... )+负责遍历你传入的所有条目(比如示例里的struct S3_1、struct S3_2等) - 内层的
$(#[$attr])*会把捕获到的所有属性逐个展开到当前条目的上方 - 双重重复组合起来,就实现了每个条目都自动附上所有指定属性的效果
使用验证
输入代码:
apply_my_attributes! { (#[derive(Debug)], #[allow(dead_code)]) struct S3_1 {} struct S3_2 {} struct S3_3 {} }
展开后会生成:
#[derive(Debug)] #[allow(dead_code)] struct S3_1 {} #[derive(Debug)] #[allow(dead_code)] struct S3_2 {} #[derive(Debug)] #[allow(dead_code)] struct S3_3 {}
完全符合需求,且是单个宏实现,保持了简洁性和可读性。
内容的提问来源于stack exchange,提问作者Olivio K
相关产品推荐
相关产品推荐

