Macro match atrributes


#1

I am playing around with an example on stack overflow as below

macro_rules! zoom_and_enhance {
    (struct $name:ident { $($fname:ident : $ftype:ty),* }) => {
        struct $name {
            $($fname : $ftype),*
        }

        impl $name {
            fn field_names() -> &'static [&'static str] {
                static NAMES: &'static [&'static str] = &[$(stringify!($fname)),*];
                NAMES
            }
        }
    }
}

zoom_and_enhance!{
struct Export {
    first_name: String,
    last_name: String,
    gender: String,
    date_of_birth: String,
    address: String
}
}

fn main() {
    println!("{:?}", Export::field_names());
}

This works fine. However, I wish to provide something similar for structs defined like

#[derive(Clone, Serialize)]
pub struct CounterSourceElement {
        output_pad: ElementPad
}

How can I get the macro to expect the attributes and maybe the optional pub ?
currently I jusr get

error: no rules expected the token #

Thanks


#2

This sort of thing should be implemented as a procedural macro, not a macro_rules macro. That way it can correctly handle attributes, visibility, generics, doc comments etc without any effort on your part.

Check out this example which is very similar to your use case.

#[derive(Clone, Serialize, FieldNames)]
pub struct CounterSourceElement {
    output_pad: ElementPad
}

#3

Thanks. I will read up on this stuff.