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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…