Struct field visitor macro

Hello, I'm looking to see if there's a crate that exists to solve a problem I have. Basically I have a struct with a large number of fields in it:

struct GameEvents {
  pub event1: GameEvent<int>,
  pub event2: GameEvent<bool>
  pub event3: GameEvent<u32>
  ...
}

I am looking for a macro to generate a 'visitor pattern' for this struct. Every field of the struct implements a common trait called EventTrait:

pub trait EventTrait {
    fn set_context(&mut self, context: EventContext);
}

and I want to generate a function which invokes this trait's method on every field of my struct:

pub fn set_context(events: &mut GameEvents, context: EventContext) {
    events.event1.set_context(context);
    events.event2.set_context(context);
    events.event3.set_context(context);
    ...
}

i.e. effectively implementing the trait for the GameEvents struct itself. Is there an existing library in Rust that can help me achieve this? It seems very similar to the sort of operation tools like serde must be performing internally, and shouldn't have much runtime overhead at all.

Disclaimer: I'm still a pretty new Rust user so I'm sure there's much better ways of doing this! As for your question, would writing a custom macro or derive macro work? A quick search on crates.io yields a ton of results, among the crates visitor, visita, and derive-visitor. The latter is also semi-recently updated compared to the other ones.

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.