You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.06 23:12:01