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 {
enum ResourceType {


struct Resource {
resource_type : ResourceType,
name : String

struct Resources {
resource1 : Resource,

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


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

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.