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

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.

Leave a Comment