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?
Each enum type has a corresponding integral type called the underlying type of the enum type. This underlying type shall be able to represent all the enumerator values defined in the enumeration. If the enum_base is present, it explicitly declares the underlying type.
To initialize an enum with values, we assign the enum with a value to a variable. We write the enum name, followed by double colon operators and the enum value name. Lastly, we specify a value between parentheses. In the example above, we assign 1 to Enabled and 0 to Disabled in the variables yes and no.
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
All variants of an enum use the same amount of memory (in case of your Foo type, 16 bytes, at least on my machine). The size of the enum's values is determined by its largest variant ( One , in your example). Therefore, the values can be stored in the array directly.
This can be done using the representation (repr
) specifier.
#[repr(u8)]
enum MyEnum { A = 0, B, C, }
Assigned values outside the range of the type will raise a compiler warning.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With