]> git.proxmox.com Git - rustc.git/blob - src/doc/reference/src/items/enumerations.md
New upstream version 1.22.1+dfsg1
[rustc.git] / src / doc / reference / src / items / enumerations.md
1 # Enumerations
2
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.
6
7 [enumerated type]: types.html#enumerated-types
8
9 Enumerations are declared with the keyword `enum`.
10
11 An example of an `enum` item and its use:
12
13 ```rust
14 enum Animal {
15 Dog,
16 Cat,
17 }
18
19 let mut a: Animal = Animal::Dog;
20 a = Animal::Cat;
21 ```
22
23 Enumeration constructors can have either named or unnamed fields:
24
25 ```rust
26 enum Animal {
27 Dog (String, f64),
28 Cat { name: String, weight: f64 },
29 }
30
31 let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
32 a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
33 ```
34
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.
38
39 ## C-like Enumerations
40
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:
45
46 ```rust
47 enum Foo {
48 Bar, // 0
49 Baz = 123,
50 Quux, // 124
51 }
52 ```
53
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.
58
59 [`repr` attribute]: attributes.html#ffi-attributes
60
61 You can also cast a c-like enum to get its discriminant:
62
63 ```rust
64 # enum Foo { Baz = 123 }
65 let x = Foo::Baz as u32; // x is now 123u32
66 ```
67
68 This only works as long as none of the variants have data attached. If it were
69 `Baz(i32)`, this is disallowed.