You are right, and it seems like the compiler normally assumes that all enum values have an valid discriminant:
use std::mem;
enum Pcode { Volume = 9, Avatar = 47 }
fn main() {
let pcode: u8 = 48;
let result = match unsafe { mem::transmute::<_, Pcode>(pcode) } {
Pcode::Volume => { "volume" },
Pcode::Avatar => { "avatar" },
//_ => { "not a valid discriminant" },
};
assert_eq!("avatar", result);
}
What I found interesting is that, if I uncomment the line which starts with _
, then compiler also checks for that, even in release build:
use std::mem;
enum Pcode { Volume = 9, Avatar = 47 }
fn main() {
let pcode: u8 = 48;
let result = match unsafe { mem::transmute::<_, Pcode>(pcode) } {
Pcode::Volume => { "volume" },
Pcode::Avatar => { "avatar" },
_ => { "not a valid discriminant" },
};
assert_eq!("not a valid discriminant", result);
}
Shouldn't the compiler just assume unsafe { mem::transmute::<_, Pcode>(pcode) }
is a valid variant of Pcode
since it is UB otherwise?