So in Rust, i am trying to iterate over a vector of u8
, and match them against cases of an enum. To do that, I set up the following code.
use std::io::prelude::*;
enum Byte {
A = 0,
B = 1,
C = 2,
D = 3
}
fn main() {
let mut buf = Vec::<u8>::new();
write!(buf, "\x01\x03\x02\x00");
match buf[1] {
Byte::A => println!("got A"),
Byte::B => println!("got B"),
Byte::C => println!("got C"),
Byte::D => println!("got D")
}
}
Assume the println!
statements could be any form of behavior, such as determining what type comes next in the byte vec, etc.
However, this results in
error[E0308]: mismatched types
--> src/main.rs:16:9
|
6 | A = 0,
| ----- unit variant defined here
...
15 | match buf[1] {
| ------ this expression has type `u8`
16 | Byte::A => println!("got A"),
| ^^^^^^^ expected `u8`, found enum `Byte`
Then, if i try to cast the enum as a u8, with Byte::A as u8
, a syntax error occurs. I am aware it's possible to convert the u8
into a Byte
, then match the converted Byte
, but that requires two match statements, one to convert, then one to compare. I am looking for a way similar as in C/C++, to treat an enum case directly as an integer in Rust. Such that my original code can function.
If there is no way to do this, a way to match against named constants in a match statement would suffice.