I was wondering if there is a way to get the field names of a struct in a macro. Consider the following example:
struct S {
a: String,
b: String
}
and a macro my_macro
, which is called like this:
my_macro!(S);
Now I want to access the field names of the struct, somehow like this:
macro_rules! my_macro {
($t:ty) => {
{
let field_names = get_field_names($t);
// do something with field_names
}
}
}
I'm pretty new to Rust and macros, so maybe I'm missing something obvious.
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 namedS
.If you define the struct as part of the macro then you can know about the fields:
… but this is, while potentially useful, often going to be a dubious thing to do.
Here is another possibility that does not require to write a macro (however, the field names will be resolved at run time):
(this solution needs the
rustc-serialize
crate)The
derive(Default)
has been added to avoid having to manually create a struct as you wanted (but a struct will still be created).This solution works by encoding the struct to a
String
in JSON format and decoding it to aJson
. From theJson
object, we can extract the field names (if it is anObject
variant).A possibly more efficient method is to write its own encoder:
which can be used as such: