3 An `enum` in Rust is a type that represents data that is one of
4 several possible variants. Each variant in the `enum` can optionally
5 have data associated with it:
10 ChangeColor(i32, i32, i32),
11 Move { x: i32, y: i32 },
16 The syntax for defining variants resembles the syntaxes used to define structs:
17 you can have variants with no data (like unit-like structs), variants with named
18 data, and variants with unnamed data (like tuple structs). Unlike
19 separate struct definitions, however, an `enum` is a single type. A
20 value of the enum can match any of the variants. For this reason, an
21 enum is sometimes called a ‘sum type’: the set of possible values of the
22 enum is the sum of the sets of possible values for each variant.
24 We use the `::` syntax to use the name of each variant: they’re scoped by the name
25 of the `enum` itself. This allows both of these to work:
29 # Move { x: i32, y: i32 },
31 let x: Message = Message::Move { x: 3, y: 4 };
34 Move { squares: i32 },
38 let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
41 Both variants are named `Move`, but since they’re scoped to the name of
42 the enum, they can both be used without conflict.
44 A value of an `enum` type contains information about which variant it is,
45 in addition to any data associated with that variant. This is sometimes
46 referred to as a ‘tagged union’, since the data includes a ‘tag’
47 indicating what type it is. The compiler uses this information to
48 enforce that you’re accessing the data in the enum safely. For instance,
49 you can’t simply try to destructure a value as if it were one of the
53 fn process_color_change(msg: Message) {
54 let Message::ChangeColor(r, g, b) = msg; // compile-time error
58 Not supporting these operations may seem rather limiting, but it’s a limitation
59 which we can overcome. There are two ways: by implementing equality ourselves,
60 or by pattern matching variants with [`match`][match] expressions, which you’ll
61 learn in the next section. We don’t know enough about Rust to implement
62 equality yet, but we’ll find out in the [`traits`][traits] section.
67 # Constructors as functions
69 An `enum` constructor can also be used like a function. For example:
75 let m = Message::Write("Hello, world".to_string());
84 fn foo(x: String) -> Message {
88 let x = foo("Hello, world".to_string());
91 This is not immediately useful to us, but when we get to
92 [`closures`][closures], we’ll talk about passing functions as arguments to
93 other functions. For example, with [`iterators`][iterators], we can do this
94 to convert a vector of `String`s into a vector of `Message::Write`s:
101 let v = vec!["Hello".to_string(), "World".to_string()];
103 let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();
106 [closures]: closures.html
107 [iterators]: iterators.html