5

I have this code:

#[derive(PartialEq, PartialOrd)]
enum ValueType {
    k1,
    k2,
    kUnknown,
}

impl ValueType {
    fn value(&self) -> u8 {
        match *self {
            ValueType::k1 => 0x0,
            ValueType::k2 => 0x1,
            ValueType::kUnknown => 0xff,
        }
    }
}

impl From<u8> for ValueType {
    fn from(orig: u8) -> Self {
        match orig {
            0x0 => return ValueType::k1,
            0x1 => return ValueType::k2,
            _ => return ValueType::kUnknown,
        };
    }
}

fn main() {
    let a: ValueType = 0x0 as u8; // error, expected enum `ValueType`, found u8
}

I would like to convert u8 to ValueType. How do I do it in Rust way?

hellow
  • 12,430
  • 7
  • 56
  • 79
JACK M
  • 2,627
  • 3
  • 25
  • 43
  • 2
    There is the [num_enum crate](https://crates.io/crates/num_enum) which can safe a lot of manual writing code – hellow Aug 19 '19 at 13:38
  • [The duplicate applied to your problem](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=0db2d36ef4bfbd78aa4e21ebe5d0fe39). – trent Aug 19 '19 at 13:51
  • @hellow Thanks for mentioning num_enum. It looks like the best crate for this type of thing because it provides a derive macro that actually implements `std::convert` traits (rather than for instance creating an unnecessary new trait or associated function). Somehow I didn't run across it when searching crates.io. – cyclaminist Aug 20 '19 at 22:58

2 Answers2

5

std::convert::Into is automatically implemented for you as a complementary trait to From so you could use its provided method and the following will compile just fine. (Into::into, unlike From::from is a method and not an associated function.)

fn main() {
    let a: ValueType = 0x0u8.into();
}
Peter Varo
  • 11,726
  • 7
  • 55
  • 77
0

You could use the associated from() method that you already implemented:

...
#[derive(PartialEq, PartialOrd, Debug)]
...

fn main() {
    let a = ValueType::from(0x0u8);
    let b: ValueType = 0x0u8.into();
    assert_eq!(a,b);
}
Gardener
  • 2,591
  • 1
  • 13
  • 22