How to pass field attributes to a macro generating a struct

50 Views Asked by At

After being told (on the quick_xml github) I cannot use #[serde(flatten)] with quick_xml and serde, I decided to emulate the behavior using a macro.

#[macro_export]
macro_rules! response {
    ($($field_name: ident: $field_type: ty),*) => {
        #[derive(Debug, Deserialize)]
        #[serde(rename_all = "PascalCase")]
        pub struct Response {
            foobar: u32,
            $($field_name: $field_type),*
        }
    }
}

#[cfg(test)]
mod test {
    use serde::Deserialize;

    #[test]
    fn test() {
        response! {
            id: i64,
            two: i32
        }
    }

    #[test]
    fn test_with_attribute() {
        response! {
            #[serde(rename = "foo")]
            one: i64,
            two: i32
        }
    }

    #[test]
    fn test_with_attributes() {
        response! {
            #[serde(rename = "foo")]
            one: i64,
            #[serde(rename = "bar")]
            two: i32
        }
    }
}

This works great! test::test() runs fine, and creates the struct I want. However, I'd like to be able to use some field attributes on the generated struct, and test::test_with_attribute() and test::test_with_attributes() both fail.

I tried using ($($(#[$field_meta: meta])* $field_name: ident: $field_type: ty),*) for the macro signature, and this compiles for all tests; but then rust tells me

field_meta is still repeating at this depth

when trying to use field_meta.

How do you pass field attributes to a macro generating a struct?

0

There are 0 best solutions below