Suppose I have an enum KindOfThing
. It looks like this:
enum KindOfThing {
Apple,
Spaghetti,
Cauliflower,
Table,
Chair,
Bed,
Desk,
Other,
}
But I would like it to look like this:
enum KindOfThing {
Food(KindOfFood),
Furniture(KindOfFurniture),
Other,
}
enum KindOfFood {
Apple,
Spaghetti,
Cauliflower,
}
enum KindOfFurniture {
Table,
Chair,
Bed,
Desk,
}
That way I can pass around KindOfFood
and KindOfFurniture
and match on them exhaustively without writing any boilerplate like this:
impl KindOfThing {
fn kind_of_food(&self) -> Option<KindOfFood> {
match self {
KindOfThing::Apple => Some(KindOfFood::Apple),
// ..etc
_ => None,
}
}
}
I need KindOfThing
to be a single byte, though. (I imagine some of you have wished for a version of Option
that would allow this, for a more concrete example.) But it's impossible for the compiler to optimize the second version down to a single byte, because that will make it impossible to take a reference to the KindOfFood
or KindOfFurniture
within.
Since #[repr(packed)]
structs will soon forbid taking references in safe code, it seems reasonable to create a new repr that enables this optimization, or possibly to allow #[repr(packed)]
on enums with this behavior.
Has this been discussed before? Any thoughts?