Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify the underlying type of an enum in Rust? [duplicate]

Tags:

enums

rust

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?

like image 493
ideasman42 Avatar asked Jan 14 '17 09:01

ideasman42


People also ask

What is the underlying type of an enum?

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.

How do you initialize an enum in Rust?

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.

Can enums have methods Rust?

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.

How are enums stored in memory Rust?

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.


1 Answers

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.

like image 192
ideasman42 Avatar answered Oct 12 '22 12:10

ideasman42