Rust 宏可以创建新的标识符吗? [英] Can a Rust macro create new identifiers?

查看:32
本文介绍了Rust 宏可以创建新的标识符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一对 setter/getter 函数,其中名称是基于共享组件自动生成的,但我找不到任何生成新名称的宏规则示例.

I'd like to create a setter/getter pair of functions where the names are automatically generated based on a shared component, but I couldn't find any example of macro rules generating a new name.

有没有办法生成像 fn get_$iden()SomeEnum::XX_GET_$enum_iden 这样的代码?

Is there a way to generate code like fn get_$iden() and SomeEnum::XX_GET_$enum_iden?

推荐答案

如果你使用 Rust >= 1.31.0 我会推荐使用我的 paste crate,它提供了一种在宏中创建连接标识符的稳定方法.

If you are using Rust >= 1.31.0 I would recommend using my paste crate which provides a stable way to create concatenated identifiers in a macro.

macro_rules! make_a_struct_and_getters {
    ($name:ident { $($field:ident),* }) => {
        // Define the struct. This expands to:
        //
        //     pub struct S {
        //         a: String,
        //         b: String,
        //         c: String,
        //     }
        pub struct $name {
            $(
                $field: String,
            )*
        }

        paste::item! {
            // An impl block with getters. Stuff in [<...>] is concatenated
            // together as one identifier. This expands to:
            //
            //     impl S {
            //         pub fn get_a(&self) -> &str { &self.a }
            //         pub fn get_b(&self) -> &str { &self.b }
            //         pub fn get_c(&self) -> &str { &self.c }
            //     }
            impl $name {
                $(
                    pub fn [<get_ $field>](&self) -> &str {
                        &self.$field
                    }
                )*
            }
        }
    };
}

make_a_struct_and_getters!(S { a, b, c });

这篇关于Rust 宏可以创建新的标识符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆