This question already has an answer here:
Given a simple enum with a few un-typed values, it might be desirable that the size of this enum use a smaller integral type then the default. For example, this provides the ability to store the enum in an array of u8
.
enum MyEnum {
A = 0,
B,
C,
}
It's possible to use a u8
array and compare them against some constants, but I would like to have the benefit of using enums to ensure all possibilities are handled in a match statement.
How can this be specified so its size_of
matches the desired integer type?
What do you mean by "We might want
them
"?The
A
,B
, andC
in your program are user-defined value constructors, not afield
as known in OOP. Instead, you may specify type for the parameters like shown below.The snippet comes from https://doc.rust-lang.org/book/enums.html.
This can be done using the representation (
repr
) specifier.Assigned values outside the range of the type will raise a compiler warning.