Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using From trait to trigger converting u8 to enum [duplicate]

Tags:

rust

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?

like image 379
JACK M Avatar asked May 25 '26 22:05

JACK M


2 Answers

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();
}
like image 84
Peter Varo Avatar answered May 27 '26 13:05

Peter Varo


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);
}
like image 37
Gardener Avatar answered May 27 '26 11:05

Gardener



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!