How can I implement generic conversion from my type to any type with a bound?

52 views Asked by At

I am trying to implement the conversion from my type to any type that can be converted from u32.

I tried impl<T> From<MyType> for T where u32: Into<T> by that apparently breaks the orphan rule. As well as impl<T> Into<T> for MyType where u32: Into<T> but that leads to a conflicting implementation. Can I achieve what I want for From / Into?

pub enum MyType {
    Case0,
    Case1,
    Case2
}

fn conv<T>(s: MyType) -> T
    where u32: Into<T> {
    match s {
        MyType::Case0 => 0.into(),
        MyType::Case1 => 1.into(),
        MyType::Case2 => 2.into(),
    }
}

impl From<MyType> for u32 {
    fn from(s: MyType) -> Self {
        conv::<Self>(s)
    }   
}

impl From<MyType> for u64 {
    fn from(s: MyType) -> Self {
        conv::<Self>(s)
    }   
}

(Yes, I know I can use C-like enums but that's not the topic of this question)

0

There are 0 answers