You can't, but you can require that a generic type is a superset of an enum T.
There are strictly limited circumstances where this is useful, but it can work around the 'cant extend enums' problem specifically with regard to events.
In the specific subset of cases where you have a library that is generic over an event type TEvent
but the library has internal events as well, you often encounter a situation where the library will take an argument of a wrapper event type, like:
enum TLibEvent<T> {
CustomEvent(T),
InternalEvent(MyInternalEventType)
}
As described in the accepted solution. However, you don't need to do this.
You can use a single flat top level event type by requiring From<MyInternalEventType>
on the generic event type to the library.
Example:
(look at the very bottom to see how this works in practice)
enum Events {
A,
B
}
#[derive(Debug)]
struct Foo<T> {
pub events: Vec<T>
}
impl<T: From<Events> + PartialEq> Foo<T>
{
pub fn new() -> Foo<T> {
Foo {
events: Vec::new()
}
}
pub fn trigger_event(&mut self, event: T) {
self.events.push(event);
}
fn internal_action(&mut self) {
self.trigger_event(T::from(Events::A));
self.trigger_event(T::from(Events::B));
}
pub fn initialize(&mut self) {
self.internal_action();
}
pub fn add(&mut self, event: T) {
self.events.push(event);
}
pub fn any_events<TIn: Into<T>>(&self, event: TIn) -> bool {
let custom_event:T = event.into();
self.events.iter().any(|e| *e == custom_event)
}
}
#[derive(PartialEq, Debug)]
enum AppEvents {
A,
B,
C
}
impl From<Events> for AppEvents {
fn from(value: Events) -> Self {
match value {
Events::A => AppEvents::A,
Events::B => AppEvents::B,
}
}
}
fn main() {
let mut foo = Foo::<AppEvents>::new();
assert!(!foo.any_events(Events::A));
assert!(!foo.any_events(Events::B));
foo.initialize();
foo.add(AppEvents::C);
// Interact with foo using either internal or external events
assert!(foo.any_events(AppEvents::C));
assert!(foo.any_events(Events::A));
assert!(foo.any_events(Events::B));
println!("{:?}", foo);
}
Rust playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=cf82e44ae4f438c0b3308b54ffb36ffa