Sub topic 7
Storing different kinds of values with an enum
This chapter assumes you can write enums and match expressions, and that you already know how to create a Vec, push to it and loop over it.
The one-type rule
A Vec<T> holds elements of a single type T. The elements sit side by side in memory and each takes the same amount of space, which is how indexing finds element i quickly. This is why vec![1, "two"] does not compile.
An enum is one type that can take several forms. If you wrap each kind of value in a variant, the Vec holds one type (the enum), and each element carries a different payload.
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
fn main() {
let row = vec![
Cell::Int(3),
Cell::Text(String::from("blue")),
Cell::Float(10.5),
];
for cell in &row {
match cell {
Cell::Int(n) => println!("int {n}"),
Cell::Text(s) => println!("text {s}"),
Cell::Float(f) => println!("float {f}"),
}
}
}The loop borrows row, so cell is a &Cell. The patterns bind n, s and f as references into the element. Nothing is moved out of the Vec.
Adding behavior to the enum
Put logic that depends on the variant in a method. The caller then does not need its own match.
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
impl Cell {
fn as_number(&self) -> Option<f64> {
match self {
Cell::Int(n) => Some(f64::from(*n)),
Cell::Float(f) => Some(*f),
Cell::Text(_) => None,
}
}
}
fn main() {
let row = vec![
Cell::Int(3),
Cell::Text(String::from("blue")),
Cell::Float(10.5),
];
let total: f64 = row.iter().filter_map(Cell::as_number).sum();
println!("{total}"); // 13.5
}row.iter() yields &Cell, which matches the &self receiver of as_number. filter_map keeps the Some values and drops the None ones, so the text cell is skipped.
Costs and limits
- Every element takes as much space as the largest variant, plus a tag that records which variant it is. A
Cellis at least as large as aString, even when it holds anInt. - You must list the variants when you define the enum. Code outside your crate cannot add new kinds.
- A
matchwithout a wildcard arm must cover every variant. Adding a variant later makes the compiler flag eachmatchthat needs updating, which is usually what you want.
If the set of types is open, or other code needs to add its own types, use a trait object instead, such as Vec<Box<dyn Shape>>.
| Need | Use |
|---|---|
| Fixed, known set of kinds | Enum |
| Callers add new kinds | Trait object |
| Exhaustive `match` checking | Enum |
Common errors
- Writing
vec![Cell::Int(1), 2]fails because2is ani32, not aCell. Wrap each value in its variant. - Matching on
row[0]by value when a variant holds aStringfails with "cannot move out of index". Match on&row[0]instead.
Exercise
Add a variant Bool(bool) to Cell. What must you change in as_number for the program to compile, and what should the new arm return if booleans are not numbers?
Show answer
The match in as_number must cover the new variant, or the compiler reports a non-exhaustive match. Add the arm Cell::Bool(_) => None. The total in main stays 13.5 because filter_map drops the None values.