有没有一种方法可以在宏中获取结构的字段名称? [英] Is there a way to get the field names of a struct in a macro?

查看:58
本文介绍了有没有一种方法可以在宏中获取结构的字段名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

struct S {
    a: String,
    b: String,
}

我有一个这样的宏:

my_macro!(S);

我想像这样访问宏中结构的字段名称:

I want to access the field names of the struct in the macro like this:

macro_rules! my_macro {
    ($t:ty) => {{
        let field_names = get_field_names($t);
        // do something with field_names
    }};
}

我是Rust和宏的新手,所以也许我缺少明显的东西.

I'm new to Rust and macros, so maybe I'm missing something obvious.

推荐答案

在解析过程中或多或少地扩展了宏.它无法访问AST或类似的东西-它只能访问传递给它的东西,对于 my_macro!(S)来说,它纯粹是应该有一个名为 S .

A macro is expanded during parsing, more or less; it has no access to the AST or anything like that—all it has access to is the stuff that you pass to it, which for my_macro!(S) is purely that there should be a type named S.

如果您将结构定义为宏的一部分,那么您就可以了解字段:

If you define the struct as part of the macro then you can know about the fields:

macro_rules! my_macro {
    (struct $name:ident {
        $($field_name:ident: $field_type:ty,)*
    }) => {
        struct $name {
            $($field_name: $field_type,)*
        }

        impl $name {
            // This is purely an example—not a good one.
            fn get_field_names() -> Vec<&'static str> {
                vec![$(stringify!($field_name)),*]
            }
        }
    }
}

my_macro! {
    struct S {
        a: String,
        b: String,
    }
}

// S::get_field_names() == vec!["a", "b"]

...但这虽然很有用,但通常会是一件令人怀疑的事情.

… but this is, while potentially useful, often going to be a dubious thing to do.

这篇关于有没有一种方法可以在宏中获取结构的字段名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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