3 An _enumeration_ is a simultaneous definition of a nominal [enumerated type] as
4 well as a set of *constructors*, that can be used to create or pattern-match
5 values of the corresponding enumerated type.
7 [enumerated type]: types.html#enumerated-types
9 Enumerations are declared with the keyword `enum`.
11 An example of an `enum` item and its use:
19 let mut a: Animal = Animal::Dog;
23 Enumeration constructors can have either named or unnamed fields:
28 Cat { name: String, weight: f64 },
31 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
32 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
35 In this example, `Cat` is a _struct-like enum variant_, whereas `Dog` is simply
36 called an enum variant. Each enum instance has a _discriminant_ which is an
37 integer associated to it that is used to determine which variant it holds.
39 ## C-like Enumerations
41 If there is no data attached to *any* of the variants of an enumeration it is
42 called a *c-like enumeration*. If a discriminant isn't specified, they start at
43 zero, and add one for each variant, in order. Each enum value is just its
44 discriminant which you can specify explicitly:
54 The right hand side of the specification is interpreted as an `isize` value,
55 but the compiler is allowed to use a smaller type in the actual memory layout.
56 The [`repr` attribute] can be added in order to change the type of the right
57 hand side and specify the memory layout.
59 [`repr` attribute]: attributes.html#ffi-attributes
61 You can also cast a c-like enum to get its discriminant:
64 # enum Foo { Baz = 123 }
65 let x = Foo::Baz as u32; // x is now 123u32
68 This only works as long as none of the variants have data attached. If it were
69 `Baz(i32)`, this is disallowed.