在Rust中,如何通过宏一次性对多个项应用多种属性?

编程语言 2026-07-08

如何在Rust中使用宏一次性对多项应用多重属性。基本上我想要一个宏,叫它 apply_my_attributes,它在接收如下输入时:

 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 {}

我得到的最接近的东西是:

macro_rules! apply_my_attributes{
    (
        ($(#[$attr:meta]),+)
        $( $name:item )+
    ) => {
        // What do I put here?
    };
}

我知道宏别名的存在,但我更愿意只用一个宏,以简洁性和可读性为优先。

解决方案

我在这里发布了来自 cafce25 的答案,他在他的 评论 中给出的,因为我认为这是对我的问题一个可行的替代方案。

macro_rules! apply_attributes {
    (
        ($(#[$attr:meta])+)
        $item:item
    ) => {
        $(#[$attr])+ $item
    };
    (
        $attrs:tt
        $( $items:item )+
    ) => {
        $( apply_attributes! { $attrs $items } )+
    };
}

pub fn func1() {
    apply_attributes! {
        (
            #[derive(Debug)]
            #[derive(Copy)]
            #[derive(Clone)]
        )
        struct S1(i32);
        struct S2(i64);
    }

    let v1 = S1(123);
    dbg!(v1);

    let v2 = S2(456);
    dbg!(v2);
    dbg!(v2.clone());
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章