Sub topic 2
Variants that carry data
This chapter covers how an enum variant can hold values. It also covers the three shapes a variant can take, how to build and read those values, and how they are stored in memory. It assumes you can read Rust syntax, have used structs and tuples, and know the basics of moves and references. You also need to be able to run a program with cargo run.
Why variants carry data
A plain enum says which of several things a value is. Often you also need the details that belong to that choice. A click has coordinates, a key press has a character, and a quit request has nothing extra. In many languages you would model this with one record that has every possible field, and you would leave most of them empty. Rust lets each variant hold exactly the data it needs.
The three variant forms
A variant can be a unit variant, a tuple variant, or a struct-like variant. One enum can mix all three.
#[derive(Debug)]
enum Event {
Quit,
KeyPress(char),
Click { x: i32, y: i32 },
Resize(u32, u32),
}
fn main() {
let events = vec![
Event::Quit,
Event::KeyPress('a'),
Event::Click { x: 10, y: 20 },
Event::Resize(800, 600),
];
for e in &events {
println!("{:?}", e);
}
}This prints:
Quit
KeyPress('a')
Click { x: 10, y: 20 }
Resize(800, 600)The forms differ as follows.
| Form | Declaration | Construction | Use when |
|---|---|---|---|
| Unit | `Quit` | `Event::Quit` | The variant carries no data |
| Tuple | `KeyPress(char)` | `Event::KeyPress('a')` | One or two fields whose meaning is obvious from position |
| Struct-like | `Click { x: i32, y: i32 }` | `Event::Click { x: 1, y: 2 }` | Several fields, or fields of the same type that need names |
Resize(u32, u32) shows the usual risk with tuple variants. Nothing in the type says which number is the width. If a reader could confuse the fields, use the struct-like form.
All variants belong to a single type. A Vec<Event> can hold all four kinds because they are all Event.
Variant names are constructors
A tuple variant name works as a function. Event::KeyPress has the type fn(char) -> Event, so you can pass it wherever a function is expected.
#[derive(Debug)]
enum Event {
KeyPress(char),
}
fn main() {
let keys: Vec<Event> = "abc".chars().map(Event::KeyPress).collect();
println!("{:?}", keys);
}This prints [KeyPress('a'), KeyPress('b'), KeyPress('c')]. Struct-like variants do not work this way. You need a closure, such as |(x, y)| Event::Click { x, y }.
Variants are not types
A variant is a value of the enum. It is not a type of its own. This function does not compile:
enum Event {
Click { x: i32, y: i32 },
}
// error: expected type, found variant `Event::Click`
fn handle_click(c: Event::Click) {}A function that only makes sense for clicks must either take the data (fn handle_click(x: i32, y: i32)) or take the whole Event and deal with the other variants. If you want a real type for the payload, wrap a struct. This is also a good choice when a variant has many fields or you want methods on its data.
#[derive(Debug)]
struct Click {
x: i32,
y: i32,
}
impl Click {
fn distance_from_origin(&self) -> f64 {
((self.x * self.x + self.y * self.y) as f64).sqrt()
}
}
#[derive(Debug)]
enum Event {
Quit,
Click(Click),
}
fn main() {
let e = Event::Click(Click { x: 3, y: 4 });
if let Event::Click(c) = &e {
println!("{:?} is {} from the origin", c, c.distance_from_origin());
}
}This prints Click { x: 3, y: 4 } is 5 from the origin.
Why not one struct with optional fields?
The alternative to an enum is a single struct where every field that might not apply is an Option.
struct EventStruct {
kind: u8, // 0 = quit, 1 = key, 2 = click
key: Option<char>,
x: Option<i32>,
y: Option<i32>,
}This design allows states that make no sense. A "quit" event might have a key. A "click" might have x but no y. The kind field can hold 200, which matches nothing. Every function that reads the struct must check these cases at run time.
With the enum, those states cannot be written. A Click always has both coordinates, and a Quit has none. The compiler enforces this, so you do not need run-time checks. The tutorial returns to this idea in the chapter on modeling states.
Reading the data back
You cannot write event.x. The value might be a Quit, which has no x. To reach the data you must first test which variant you have, and a pattern does that. The next chapter covers match in detail. For now, here is a pattern in if let and in match, used to change data in place.
#[derive(Debug)]
enum Event {
Quit,
Click { x: i32, y: i32 },
}
fn main() {
let mut e = Event::Click { x: 1, y: 2 };
match &mut e {
Event::Click { x, .. } => *x += 10,
_ => {}
}
println!("{:?}", e);
}This prints Click { x: 11, y: 2 }. Three details matter here:
&mut eborrows the enum mutably, soxis a&mut i32. That is why the code writes*x += 10...ignores the fields you do not name._matches any other variant. Here, that meansQuit.
Generic variants
A variant's data can use generic types, which is how Option<T> and Result<T, E> are built. You can define your own:
#[derive(Debug)]
enum Reply<T> {
Value(T),
Refused(String),
}
fn main() {
let a: Reply<i32> = Reply::Value(7);
let b: Reply<i32> = Reply::Refused("busy".to_string());
println!("{:?} {:?}", a, b);
}The type parameter is part of the enum's type. Reply<i32> and Reply<String> are different types. The String in Refused is the same in both.
How the data is stored
An enum value holds one variant at a time. Rust stores a tag that records which variant is active, followed by space for that variant's fields. The fields of different variants share the same space. The size of the whole enum is therefore based on the largest variant plus the tag, with some padding. It is not the sum of all variants.
use std::mem::size_of;
#[allow(dead_code)]
enum Packet {
Ping,
Data([u8; 64]),
}
fn main() {
println!("Packet is {} bytes", size_of::<Packet>());
assert!(size_of::<Packet>() >= 65);
}Packet takes at least 65 bytes, even when the value is Ping. The exact figure depends on the platform and the compiler. This matters when one variant is much larger than the rest. Every value of the enum, including the small ones, takes the large size. If that wastes memory in a large collection, store the big payload behind a Box (a pointer to heap data), as covered in the chapter on recursive enums.
Common errors
- Struct-like construction with the wrong syntax.
Event::Click(1, 2)fails for a struct-like variant. WriteEvent::Click { x: 1, y: 2 }. - Reading a field without a pattern.
e.xis an error even when you know the variant. Match first. - Moving data out by accident. Matching
eby value can move aStringout of the enum and leaveeunusable. Match on&eto borrow instead. The chapter on binding modes covers this. - Treating a variant as a type, as shown above.
- Forgetting the type parameter.
Reply::Value(7)can usually be inferred, butReply::Refused("x".to_string())alone gives the compiler noT, so you need an annotation.
Exercises
Exercise
You are modeling a payment method. A card has a number (String) and an expiry year (u16). A bank transfer has an IBAN (String). Cash has no data. Write the enum, and explain why this is safer than a struct with a number: Option<String> field and an iban: Option<String> field.
Show answer
enum Payment { Card { number: String, expiry_year: u16 }, BankTransfer(String), Cash }. With the enum, a Card always has both fields, a BankTransfer always has an IBAN, and Cash has neither. The optional-field struct allows a value with both fields set, or neither set, and the compiler cannot tell that these are mistakes. The enum makes those states impossible to write.
Exercise
Given enum Event { Quit, Click { x: i32, y: i32 } } and let e = Event::Click { x: 5, y: 6 };, why does println!("{}", e.x); fail to compile, and what is the smallest change that prints the value of x?
Show answer
The value of e might be any variant, and Quit has no field x, so field access on the enum is rejected. Use a pattern: if let Event::Click { x, .. } = e { println!("{}", x); }. The pattern checks the variant first, then binds x.