Compiling playground v0.0.1 (/playground)
error[E0605]: non-primitive cast: `RelocType` as `u8`
--> src/main.rs:32:20
|
32 | println!("{}", rtype as u8);
| ^^^^^^^^^^^ an `as` expression can be used to convert enum types to numeric types only if the enum type is unit-only or field-less
|
= note: see https://doc.rust-lang.org/reference/items/enumerations.html#casting for more information
For more information about this error, try `rustc --explain E0605`.
error: could not compile `playground` (bin "playground") due to 1 previous error
It's possible to bypass the “non-primitive cast” and fetch the discriminant even from an enum with fields, but that wouldn't get you what you want — all UNKNOWNs have the discriminant 4, not the u8 field value. (Note that UNKNOWN(0), UNKNOWN(1), UNKNOWN(2), and UNKNOWN(3) are all valid values of your enum, so the field can't be stored with the discriminant. You'd need a special U8GreaterThan3 type to achieve that.
I tried writing impl Into<u8> for RelocType (isn't it equivalent in this case) but could not figure out how to get the value associated with UNKNOWN variant.
From the docs: "One should avoid implementing Into and implement From instead. Implementing From automatically provides one with an implementation of Into thanks to the blanket implementation in the standard library."
Sorry, it was a hypothetical thing that doesn't really exist in Rust today. It would be a type that is similar to NonZeroU8 except that instead of excluding 0 from its possible values, it would exclude all of 0, 1, 2, 3.
This is a parsing code, I want to know what the value was while serializing/printing even though it did not map to a known variant, so returning Error is not really useful.
My implementation is taken from C api. Your solution is new to me but looks like a good alternative.