Hey there,
I needed a very large enum lately, while creating it I wondered why are there no generic types in enum variants?
Obviously you can define global types, but this always leads to different, non compatible types.
My concept of such an enum would look like this:
pub enum MyEnum {
TupleLikeVariant<T: Clone + Debug>(T),
StructLikeVariant<S: Clone> {
content: S
},
NonGenericVariant(u32)
}
This enum could be initialized just like every other enum aswell:
pub fn main() {
let v1: MyEnum = MyEnum::TupleLikeVariant::<String>(String::from("generic string variant"));
let v2: MyEnum = MyEnum::StructLikeVariant::<usize>{ content: 123usize };
let v3: MyEnum = MyEnum::TupleLikeVariant(1.5);
}
Obiously you should be able to switch by patterns:
impl Clone for MyEnum {
fn clone(&self) -> Self {
match self {
MyEnum::TupleLikeVariant<T>(value) => {
MyEnum::TupleLikeVariant(value.clone())
}
MyEnum::StructLikeVariant {content: value} => {
MyEnum::StructLikeVariant {
content: value.clone()
}
}
MyEnum::NonGenericVariant(value) => MyEnum::NonGenericVariant(value.clone())
}
}
}
and use it in if clauses:
pub fn print_it(enum_value: MyEnum) {
if let MyEnum::TupleLikeVariant::<T>(value) = enum_value {
println!("{:?}", enum_value);
}
}
the only problem I've come up with is defining explizit representation values to the enum value:
pub enum MyEnum {
TupleLikeVariant<T: Clone + Debug>(T) = 42;
}
which is obviously not possible due to multiple implementation of one variant. But I guess this could be solved.
Is there any other reason why it would not work and why it is not implemented?