Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

rust - Is there a way to get the field names of a struct in a macro?

Consider the following example:

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

I have a macro which is called like this:

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
    }};
}

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...