0

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.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
Alex Vergara
  • 1,766
  • 1
  • 10
  • 29

1 Answers1

3

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"),
};
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • Sorry, but I am not being able to impl your solution. Can you provide it in the context of the code? Or another workaround? I can't even compile the first line. `Value is not found on this scope`. – Alex Vergara Apr 05 '22 at 20:11
  • Oh, I always swap the order. It should be `lit: value`. Will edit. – Chayim Friedman Apr 05 '22 at 21:03
  • @Pyzyryab I don't really grasp the intent in your code (why do you flatten the paths?) So I cannot help you more (and in additiona, this is not a question for SO. If you're stuck at something, please explain exactly where), but this should give you the main idea. – Chayim Friedman Apr 05 '22 at 21:07
  • oh, forgot about this. Your answer is perfectly ok – Alex Vergara Nov 17 '22 at 10:46