How I can generate code per struct field

I actively learn rust and for that purpose write random programs.
Now I write a small game. I need to make resource manager or something similar.
Once I read that rust provide macro that work like visitor pattern and generate code for every field of your structure. But I can't find example. Also is it possible to do that only for fields that implement certain trait ?

eunm ResourceType {
    type1(something),
...
enum ResourceType {
type1(SomeType),

}

struct Resource {
resource_type : ResourceType,
name : String
}

#[derive(SomeMagickMacro)]
struct Resources {
resource1 : Resource,
    ...
}

impl Resources {
    fn new() -> Resources {
        let result = Resources {
            resource1 : Resource{ resource_type:ResourceType::type1(1), name:String::from("some name")}
                ...
        };

        result.SomeGeneratedFunction();
        result
    }
}

It sounds like you're looking for procedural macros (or to be more specific, 'derive' macros). There's a good set of exercises for learning them here.

No - macros are run before type resolution happens.

1 Like