我正在使用泛型专业化在某些枚举数据结构上具有自定义编译时类型:
pub trait MyEnumState{}
// All state are Zero Sized Type
pub struct State1; impl MyEnumState for State1{};
pub struct State2; impl MyEnumState for State2{};
// Note : I don't know is there is a PhantomData<S> for an enum
pub enum MyEnum<S: MyEnumState> {
A,
B,
C(i32), // Can also have some data
// ... long enum
}
现在我希望能够对它们进行转换:相同的值,不同的类型
// How to avoid this mess ???
impl MyEnum<State1> {
pub fn to_state2(self) -> MyEnum<State2> {
match self {
MyEnum::A => MyEnum::A,
MyEnum::B => MyEnum::B,
MyEnum::C(v) => MyEnum::C(v),
}
}
}
// I can proably make a generic function
// ```
// fn cast
// <StateBegin : MyEnumState, StateEnd : MyEnumState>
// (val MyEnum<StateBegin>) -> MyEnum<StateEnd> { ... }
// ```
// to avoid repetition but I still have at least 1 giant match to implement
impl MyEnum<State2> { ... }
impl<S : MyEnumState> MyEnum<S>
{
pub fn to_state<NewState : MyEnumState>(self) -> MyEnum<NewState>
{
// how ?!
}
}
这只是一个简单的例子,目标是有0 个匹配语句以避免匹配所有现有的枚举变体。