首页 > 解决方案 > 可选模式内的重复

问题描述

我正在尝试根据可选模式的存在选择性地生成一个结构$( … )?

macro_rules! accounts_struct {
    (
        $( #[seeds: struct $StructSeedsName:ident] )?
        struct $StructAccountsName:ident {
            $(
                pub $account:ident,
            )*
        }
    ) => {
        pub struct $StructAccountsName {
            $(
                pub $account: String,
            )*
        }
        
        $(
            pub struct $StructSeedsName {
                $(
                    pub $account: u8,
                )*
            }
        )?
    }
}

accounts_struct! {
    #[seeds: struct Seeds]
    struct Accounts {
        pub foo,
        pub bar,
    }
}

游乐场

不幸的是,看起来我不允许这样做:

error: meta-variable `StructSeedsName` repeats 1 time, but `account` repeats 2 times
  --> src/lib.rs:16:10
   |
16 |           $(
   |  __________^
17 | |             pub struct $StructSeedsName {
18 | |                 $(
19 | |                     pub $account: u8,
20 | |                 )*
21 | |             }
22 | |         )?
   | |_________^

我可以使用什么作为解决方法?

标签: rustmacros

解决方案


作为最后的手段,您可以像这样重复自己,以涵盖可选部分存在和不存在的情况

macro_rules! accounts_struct {
    (
        #[seeds: struct $StructSeedsName:ident]
        struct $StructAccountsName:ident {
            $(
                pub $account:ident,
            )*
        }
    ) => {
        pub struct $StructAccountsName {
            $(
                pub $account: String,
            )*
        }
        
        
        pub struct $StructSeedsName {
            $(
                pub $account: String,
            )*    
        }
    };
    (
        struct $StructAccountsName:ident {
            $(
                pub $account:ident,
            )*
        }
    ) => {
        pub struct $StructAccountsName {
            $(
                pub $account: String,
            )*
        }
    };
}

推荐阅读