Sub topic 2
Variants that carry data
This chapter assumes you know Rust structs and tuples, have defined a plain enum with unit variants, and can build a program with cargo.
Why variants carry data
A plain enum says which kind of thing you have. Often you also need the details that belong to that kind. A circle needs a radius. A rectangle needs a width and a height. A "quit" command needs nothing.
You could use one struct with optional fields for every possible detail. That allows nonsense, such as a circle with a width. In Rust, each variant of an enum can hold its own data. A value then has exactly the fields of its variant.
Three shapes of variant
A variant can take one of three forms.
| Form | Syntax | Fields accessed by |
|---|---|---|
| Unit | `Empty` | No fields |
| Tuple | `Triangle(f64, f64, f64)` | Position |
| Struct-like | `Circle { radius: f64 }` | Name |
One enum can mix all three forms.
#[derive(Debug)]
enum Shape {
Empty,
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
fn main() {
let shapes = [
Shape::Empty,
Shape::Circle { radius: 1.0 },
Shape::Rectangle { width: 2.0, height: 3.0 },
Shape::Triangle(3.0, 4.0, 5.0),
];
for shape in &shapes {
println!("{shape:?}");
}
}This prints:
Empty
Circle { radius: 1.0 }
Rectangle { width: 2.0, height: 3.0 }
Triangle(3.0, 4.0, 5.0)Every value has the type Shape, so the array holds all four. The #[derive(Debug)] line lets {:?} print each value.
Choose the struct-like form when fields have a meaning that a position does not convey. Rectangle { width, height } is clearer than Rectangle(2.0, 3.0). Choose the tuple form for one or two obvious fields, or when the fields are all the same kind, like the three sides of a triangle.
Constructing values
You build a value by naming the enum and the variant, then supplying the data. Struct-like variants use braces with field: value. Tuple variants look like function calls, and they really are functions. Message::Text has the type fn(String) -> Message, so you can pass it where a function is expected.
#[derive(Debug)]
enum Message {
Quit,
Text(String),
Move { x: i32, y: i32 },
}
fn main() {
let mut messages: Vec<Message> = ["hi", "there"]
.iter()
.map(|s| s.to_string())
.map(Message::Text)
.collect();
messages.push(Message::Move { x: 1, y: -1 });
messages.push(Message::Quit);
println!("{messages:?}");
}This prints [Text("hi"), Text("there"), Move { x: 1, y: -1 }, Quit].
How the data is stored
An enum value holds one variant at a time. Rust stores a hidden tag that records which variant is active. It also reserves space for the largest variant's data. A Shape is therefore about as large as its biggest variant plus the tag. Small variants do not shrink the type.
Exercise
Define an enum Event with three variants: Click with fields x and y (both i32), KeyPress holding one char, and Close with no data. Which form is each variant, and how do you create a Click at 10, 20?
Show answer
Click is struct-like, KeyPress is a tuple variant, and Close is a unit variant. Define it as enum Event { Click { x: i32, y: i32 }, KeyPress(char), Close }. Create the click with Event::Click { x: 10, y: 20 }.