0

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)

Simon
  • 860
  • 7
  • 23
  • Macros? Custom trait? A conversion function? – Chayim Friedman Aug 23 '22 at 11:57
  • I'd like to have the Into / From traits automatically ;D A conversion function is basically what I wrote there. And I guess a macro would allow me to do it for all the types I can think of but not other ones? – Simon Aug 23 '22 at 12:15
  • Yes regarding the macro. I don't think you can use `From`/`Into`. – Chayim Friedman Aug 23 '22 at 12:16
  • 1
    Probably helpful: [Transitive From/Into - why, and why not? (r/rust)](https://www.reddit.com/r/rust/comments/cdmopy/transitive_frominto_why_and_why_not/) – EvilTak Aug 23 '22 at 16:12

0 Answers0