使用宏,如何获取结构字段的唯一名称?

Kro*_*tan 1 macros rust

假设我调用了一些宏:

my_macro!(Blah, (a, b, c));
Run Code Online (Sandbox Code Playgroud)

它输出如下内容:

struct Blah {
    a: i32,
    b: i32,
    c: i32
}
impl Blah {
    fn foo() -> i32 {
        a + b + c
    }
}
Run Code Online (Sandbox Code Playgroud)

(人工示例)

这些字段对结构来说是私有的,但我需要允许重新定义。所以,输入

my_macro!(Blah, (a, b, c, a));
Run Code Online (Sandbox Code Playgroud)

会产生类似的东西:

struct Blah {
    a1: i32,
    b: i32,
    c: i32,
    a2: i32
}
impl Blah {
    fn foo() -> i32 {
        a1 + b + c + a2
    }
}
Run Code Online (Sandbox Code Playgroud)

命名方案不需要遵循任何逻辑模式。

这可能吗?

dto*_*nay 5

我的mashup箱子为您提供了扩展的方式my_macro!(Blah, (a, b, c, a))进入领域x_axx_bxxx_cxxxx_d如果这样的命名,会为你工作。我们x为每个字段添加一个附加项,然后是下划线,然后是原始字段名称,这样字段就不会出现名称冲突。这种方法适用于任何 >= 1.15.0 的 Rust 版本。


#[macro_use]
extern crate mashup;

macro_rules! my_macro {
    ($name:ident, ($($field:ident),*)) => {
        my_macro_helper!($name (x) () $($field)*);
    };
}

macro_rules! my_macro_helper {
    // In the recursive case: append another `x` into our prefix.
    ($name:ident ($($prefix:tt)*) ($($past:tt)*) $next:ident $($rest:ident)*) => {
        my_macro_helper!($name ($($prefix)* x) ($($past)* [$($prefix)* _ $next]) $($rest)*);
    };

    // When there are no fields remaining.
    ($name:ident ($($prefix:tt)*) ($([$($field:tt)*])*)) => {
        // Use mashup to define a substitution macro `m!` that replaces every
        // occurrence of the tokens `"concat" $($field)*` in its input with the
        // resulting concatenated identifier.
        mashup! {
            $(
                m["concat" $($field)*] = $($field)*;
            )*
        }

        // Invoke the substitution macro to build a struct and foo method.
        // This expands to:
        //
        //     pub struct Blah {
        //         x_a: i32,
        //         xx_b: i32,
        //         xxx_c: i32,
        //         xxxx_a: i32,
        //     }
        //
        //     impl Blah {
        //         pub fn foo(&self) -> i32 {
        //             0 + self.x_a + self.xx_b + self.xxx_c + self.xxxx_a
        //         }
        //     }
        m! {
            pub struct $name {
                $(
                    "concat" $($field)*: i32,
                )*
            }

            impl $name {
                pub fn foo(&self) -> i32 {
                    0 $(
                        + self."concat" $($field)*
                    )*
                }
            }
        }
    };
}

my_macro!(Blah, (a, b, c, a));

fn main() {}
Run Code Online (Sandbox Code Playgroud)