In a discord discussion today, the question of using enum variants in a match for another type came up.
Given an enum
and a u8
let x: u8 = 0;
#[repr(u8)]
enum A {
B
}
the goal is to use the enum discriminants for matching a u8
value. The simple “obvious” case doesn’t work, because of a type mismatch:
match x {
A::B => ..,
_ => ..,
};
it feels like you should be able to use as
to get the types to line up, but that doesn’t work either (as
is not part of pattern syntax):
match x {
A::B as u8 => ..,
_ => ..,
};
instead you need to indirectly put the as
elsewhere via one of these less-than-ideal workarounds:
const B_U8 : u8 = A::B as u8;
match x {
B_U8 => ..,
_ => ..,
};
match x {
_ if x == (A::B as u8) => ..,
_ => ..,
};
Is there some other way to do this I’ve missed (not counting using macros to automate some of the repetition)
What would be necessary to / the implications of allowing match arms like A::B as u8 =>
It’s a const expression for a literal value (aside, the reference doesn’t seem to explicitly describe using enum variants as match patterns in its grammar, but I assume it’s effectively part of a Literal Pattern). I ask now because, perhaps with all the work being done to enable const functions lately, it’s a good time to consider.