Is there a way for me to avoid duplicate enum declarations without using `dyn`?

I am making a simple event system, where clients can register to receive callbacks when a certain event occurs. This is how I'm structuring my code:

pub enum EventName {
    PlayCard,
}

pub enum EventData {
    PlayCard(CardId),
}

pub type CallbackFn = fn(game: &mut GameState, data: EventData);

pub struct EventHandler {
    event: EventName,
    handler: CallbackFn,
}

pub struct Card {
  handlers: Vec<EventHandler>
}

This approach works well, but it requires the creation of two separate enums that I need to keep in sync (EventName and EventData) -- the first one is required to indicate which type of events to handle, and the second one provides the arguments for the event itself. What I'd really like would be to unify this into a single definition, perhaps by using generics?

I'm aware I could solve this by using standard boxing/dyn Trait patterns, but I was hoping for something with the same performance characteristics as this code.

For this specific case you can use Discriminant to replace names.

But with this design every callbacks should be able to receive every kind of data. Is it intentional? If not, it would be optimal to have EventHandler as a enum over callback functions which receive specific variants. You can use macro to declare both event and handler types at once.

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.