An enum in Rust is a custom data type representing data that can be any kind among several possible variants. Each variant in the enum can optionally have data associated with it. An enumerated type is defined using the enum
keyword before the name of the enumeration. It also consists of methods.
Empty enums are similar to !
and can never be instantiated. They are used mainly to mess with the type system in interesting ways.
The simplest form of enum is one where none of the variants have any fields, a fieldless enum.
fn main() { enum SomeEnum { Variant1, Variant2, Variant3, } }
Fieldless enums may also specify the value of their discriminants explicitly.
fn main() { enum SomeEnum { Variant22 = 22, Variant44 = 44, Variant45, } }
Enums with at least one variant with fields are called data-carrying enums. Note that for this definition, it is not relevant whether the variant fields are zero-sized.
fn main() { enum Foo { Bar(()), Baz, } }
RELATED TAGS
CONTRIBUTOR
View all Courses