From my perspective (which may be colored by interacting with C a lot) conversion of integers to (field-less) enums is a frequent operation.
Rust has a built-in way to convert an enum to an integer, but not the other way. The current workarounds are pretty bad IMHO:
matchfor mapping every integer to every variant. This is unacceptably tedious, and the need to manually copy integers leaves room for errors.
Use two crates and a macro derive. I’m generally OK with using dependencies for small things, but that is such an overkill to merely check whether an integer is in range.
mem::transmute(). I’ve used it, because that is the only one-liner available in Rust, and it has backfired terribly by causing undefined behavior and memory corruption elsewhere in the program.
I wonder if many people will make the same mistake with
transmute, because especially with
#[repr(C)] it feels like a harmless no-op integer cast, and not a program-destroying nasal demon.
Since there isn’t a clearly good solution to this problem, Googling for solutions also brings poor results. Depending on how you phrase it you may find old Rust book about enums (which does not contain any solution), GitHub issues about now-dead
FromPrimitive, and some forum threads which suggest
transmute or look outdated.
So I think Rust should have a single good solution for making a field-less enum from an integer.