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

标签 macros rust

假设我这样调用了一些宏:

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

它的输出是这样的:

struct Blah {
    a: i32,
    b: i32,
    c: i32
}
impl Blah {
    fn foo() -> i32 {
        a + b + c
    }
}

(人工示例)

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

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

将生成如下内容:

struct Blah {
    a1: i32,
    b: i32,
    c: i32,
    a2: i32
}
impl Blah {
    fn foo() -> i32 {
        a1 + b + c + a2
    }
}

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

这可能吗?

最佳答案

我的 mashup crate 为您提供了一种将 my_macro!(Blah, (a, b, c, a)) 扩展到字段 x_a, xx_b, xxx_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() {}

关于macros - 使用宏,如何获得结构字段的唯一名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193846/

相关文章:

c++ - 为什么goto这个宏定义会导致程序崩溃?

这里可以使用 stringize 宏吗?

reference - 如何在 Rust 中以最惯用的方式将 Option<&T> 转换为 Option<T>?

c - 枚举C中的结构字段

c - C 中的宏和前/后增量

rust - 如何在 Rust 中绑定(bind) `Output` 类型的运算符特征?

testing - 在文档测试中使用本地模块时出错

binding - let-rebinding 和标准赋值有什么区别?

c - C 中用于获取/设置数组条目的宏

arrays - 如何返回对局部变量的引用,指定其生命周期与自身相同?