Sub topic 7
Storing Different Kinds of Values with an Enum
A Vec<T> holds elements of exactly one type. Real data is often mixed: a spreadsheet row with numbers and text, a list of parsed tokens, a queue of commands. This chapter shows how to model that with an enum, how to read and change the values, and when to use trait objects instead.
This chapter assumes you can define enums with data in their variants, use match and if let, and know the difference between &, &mut and moved values. It also assumes you have read the earlier chapters on creating, indexing and iterating over a Vec.
Why a Vec cannot mix types
Every element of a Vec<T> has the same type T, so every element has the same size. That is what lets v[i] find an element by arithmetic: the start address plus i times the element size. A literal such as vec![1, "two"] fails to compile with a mismatched types error, because i32 and &str are different types with different sizes.
The fix is to make the different kinds of values into one type. An enum does this. Each variant carries its own data, but the enum as a whole is a single type, so Vec<Cell> is legal.
A Vec of enum values
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
impl Cell {
fn describe(&self) -> String {
match self {
Cell::Int(n) => format!("int {n}"),
Cell::Text(s) => format!("text {s}"),
Cell::Float(f) => format!("float {f}"),
}
}
}
fn main() {
let row = vec![
Cell::Int(3),
Cell::Text(String::from("blue")),
Cell::Float(10.5),
];
for cell in &row {
println!("{}", cell.describe());
}
}This prints int 3, text blue and float 10.5.
Three details matter here:
for cell in &rowborrows theVec, socellis a&Cell. Matching on a reference bindsn,sandfas references too, and nothing is moved out of the row.- The
matchhas no_arm. The compiler checks that every variant is handled. If you addBool(bool)toCelllater, this code stops compiling until you handle it. That is the main advantage of an enum: the full list of possible kinds is closed and visible. - Putting the
matchinside a method keeps the variant handling in one place instead of repeating it at every call site.
Memory layout
A value of an enum type is a tag (which variant it is) plus room for the data of the largest variant. Every Cell in the Vec therefore takes the same amount of space, however small its current variant is.
use std::mem::size_of;
#[allow(dead_code)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
fn main() {
assert!(size_of::<Cell>() >= size_of::<String>());
println!("Cell is at least as big as its largest variant");
}The exact size depends on the compiler and platform, so assert a bound instead of printing a number. If one variant is far larger than the rest, every element pays for it. A common fix is to box the large variant, for example Big(Box<BigData>), so the element only holds a pointer.
Reading and changing enum elements
To work with only one variant, use if let or filter_map. To change a value in place, iterate with iter_mut:
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
fn main() {
let mut row = vec![
Cell::Int(3),
Cell::Text(String::from("blue")),
Cell::Int(4),
Cell::Float(10.5),
];
for cell in row.iter_mut() {
if let Cell::Int(n) = cell {
*n *= 10;
}
}
let total: i32 = row
.iter()
.filter_map(|c| match c {
Cell::Int(n) => Some(*n),
_ => None,
})
.sum();
println!("{total}");
println!("{:?}", row);
}The output is 70, then [Int(30), Text("blue"), Int(40), Float(10.5)].
In the first loop, cell is a &mut Cell. Matching it against Cell::Int(n) makes n a &mut i32, so you write *n *= 10. In the second step, filter_map keeps only the Some values, which turns a heterogeneous row into a plain stream of i32.
Using _ => None is a deliberate choice here. You want to ignore the other variants, and a wildcard says so. Elsewhere, prefer listing all variants so the compiler warns you when a new one appears.
Building rows with From
Typing Cell::Int(...) for every element gets noisy. Implementing From for each payload type lets you use .into():
#[derive(Debug)]
enum Cell {
Int(i32),
Text(String),
Float(f64),
}
impl From<i32> for Cell {
fn from(n: i32) -> Self {
Cell::Int(n)
}
}
impl From<&str> for Cell {
fn from(s: &str) -> Self {
Cell::Text(s.to_string())
}
}
impl From<f64> for Cell {
fn from(f: f64) -> Self {
Cell::Float(f)
}
}
fn main() {
let row: Vec<Cell> = vec![7_i32.into(), "red".into(), 2.5_f64.into()];
println!("{:?}", row);
}This prints [Int(7), Text("red"), Float(2.5)]. The type annotation on row tells into which target type to produce. The numeric suffixes (7_i32, 2.5_f64) remove any doubt about which From impl applies.
Enum or trait object
An enum is not the only way to hold mixed values. If the kinds share behavior, you can store trait objects instead:
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.14159 * self.0 * self.0
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle(1.0)), Box::new(Square(2.0))];
let total: f64 = shapes.iter().map(|s| s.area()).sum();
println!("{total:.2}");
}This prints 7.14. Each Box<dyn Shape> is a fixed-size pointer to a value on the heap, which is how elements of different sizes fit in one Vec.
| Question | Enum | `Box<dyn Trait>` |
|---|---|---|
| Set of kinds | Closed, defined in one place | Open, other code can add types |
| Adding a new operation | Write one new function with a `match` | Add a method to the trait and every impl |
| Adding a new kind | Edit the enum and every `match` | Write a new type and an impl |
| Storage | Inline in the `Vec`, sized by the largest variant | One heap allocation per element |
| Access to the data | Pattern match on the exact variant | Only the trait's methods |
Choose an enum when you want to inspect and destructure the data, such as parsed tokens or table cells. Choose trait objects when callers only need a common interface and new types may come from elsewhere.
Common mistakes
- Wildcard arms that hide new variants.
_ => {}compiles forever, even after the enum grows. Use it only when ignoring the rest is the real intent. - Matching an owned value inside a loop over a borrowed
Vec. If you writematch *cell { Cell::Text(s) => ... }, the compiler reports that it cannot move out of a borrow. Match oncellitself, or on&*cell, and let the bindings be references. - Holding a reference across a
push. The rule from the borrowing chapter still applies. A&Cellobtained from&row[0]blocksrow.push(...)while the reference is alive. - One giant variant. A single large variant inflates every element. Box it.
Exercise
You have enum Token { Num(f64), Op(char), Ident(String) } and a tokens: Vec<Token>. Write the expression that returns the sum of all Num values, and explain why you do not need to clone any Token.
Show answer
tokens.iter().filter_map(|t| match t { Token::Num(n) => Some(*n), _ => None }).sum::<f64>(). iter() yields &Token, so the match binds n as &f64. Dereferencing with *n copies the f64, which is Copy. The Ident(String) variants are never moved or cloned because the wildcard arm just returns None.
Exercise
A teammate writes let v: Vec<Box<dyn Shape>> = ... to hold three known shapes: Circle, Square and Triangle. Later code needs to read Triangle's base and height directly. Which approach fits better, and why?
Show answer
An enum such as enum Shape { Circle(f64), Square(f64), Triangle { base: f64, height: f64 } } fits better. The set of shapes is closed, and an enum lets you pattern match to reach the exact fields. A Box<dyn Shape> exposes only the trait's methods, so you cannot read base and height without adding methods to the trait or using downcasting.