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?
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();
}
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With