简体   繁体   中英

Value of a field attribute on a proc macro

I have this struct:

pub struct Thing {
    pub some_field: i32,

    #[my_attr = some_value]
    pub field_attr: String
}

How can I recover the data on the right side of the equals? I can recover perfectly fine the left side.

pub fn new(name: &Ident, raw_helper_attributes: &[Attribute], ty: &Type) -> syn::Result<Self> {
        // Getting the name of attributes put in front of struct fields
        let helper_attributes = raw_helper_attributes
            .iter()
            .map(|attribute| {
                attribute
                    .path
                    .segments
                    .iter()
                    .map( |segment| {
                        &segment.ident
                    })
                    .collect::<Vec<_>>()
            })
            .flatten()
            .collect::<Vec<_>>();

        let attribute_type = if helper_attributes.len() == 1 {
            let helper_attribute = helper_attributes[0];
            Some(EntityFieldAnnotation::try_from(helper_attribute)?)
        } else if helper_attributes.len() > 1 {
            return Err(
                syn::Error::new_spanned(
                    name, 
                    "Field has more than one attribute"
                )
            );
        } else { None };

        Ok(
            Self {
                name: name.clone(),
                field_type: ty.clone(),
                attribute: attribute_type,
            }
        )
    }

For short, I ommited the rest of the code of the macro for summarize.

Use Attribute::parse_meta() :

let (path, value) = match attribute.parse_meta().unwrap() {
    syn::Meta::NameValue(syn::MetaNameValue {
        path,
        lit: syn::Lit::Str(s),
        ..
    }) => (path, s.value()),
    _ => panic!("malformed attribute syntax"),
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM