Rust Enums
An enum (short for enumeration) is a type whose value is exactly one of a fixed set of variants. A traffic light is red, yellow or green; a payment is cash, card or voucher. Enums let you express that "one of these" idea directly, and the compiler then makes sure you handle every case.
Defining a simple enum
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
fn main() {
let heading = Direction::East;
let opposite = Direction::West;
println!("Heading {:?}, turning to {:?}", heading, opposite);
}Heading East, turning to West
Variants are written with the enum name and ::, as in Direction::East. Each variant is a possible value of the type Direction.
Using match with enums
match is the natural partner of enums. It compares a value against each variant and runs the matching arm. The compiler checks that the match is exhaustive — if you forget a variant, your code will not compile.
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn cents(coin: &Coin) -> u32 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
let purse = [Coin::Quarter, Coin::Dime, Coin::Penny, Coin::Penny];
let mut total = 0;
for c in &purse {
total += cents(c);
}
println!("The purse holds {} cents", total);
}The purse holds 37 cents
Forget Coin::Quarter and you get:
error[E0004]: non-exhaustive patterns: `&Coin::Quarter` not coveredVariants that carry data
This is where Rust enums become much more powerful than in many other languages: each variant can hold its own data, with different types and amounts per variant.
enum Shape {
Circle(f64), // radius
Rectangle(f64, f64), // width, height
Triangle { base: f64, height: f64 },
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(r) => 3.14 * r * r,
Shape::Rectangle(w, h) => w * h,
Shape::Triangle { base, height } => 0.5 * base * height,
}
}
fn main() {
let shapes = vec![
Shape::Circle(2.0),
Shape::Rectangle(3.0, 4.0),
Shape::Triangle { base: 6.0, height: 5.0 },
];
for s in &shapes {
println!("Area: {:.2}", area(s));
}
}Area: 12.56
Area: 12.00
Area: 15.00
In each match arm, the pattern pulls out the data stored in the variant (r, w, h, …) so you can use it. A Vec<Shape> can mix all three kinds of shapes, because they are all the same type.
| Variant style | Example | How to match it |
|---|---|---|
| No data | Quit |
Msg::Quit => ... |
| Tuple-like | Move(i32, i32) |
Msg::Move(x, y) => ... |
| Struct-like | Write { text: String } |
Msg::Write { text } => ... |
Methods on enums
Just like structs, enums can have an impl block with methods.
enum Command {
Say(String),
Add(i32, i32),
Quit,
}
impl Command {
fn run(&self) -> String {
match self {
Command::Say(text) => format!("You said: {}", text),
Command::Add(a, b) => format!("{} + {} = {}", a, b, a + b),
Command::Quit => String::from("Goodbye!"),
}
}
fn is_quit(&self) -> bool {
matches!(self, Command::Quit)
}
}
fn main() {
let script = [
Command::Say(String::from("hello")),
Command::Add(4, 9),
Command::Quit,
];
for cmd in &script {
println!("{}", cmd.run());
if cmd.is_quit() {
println!("(stopping)");
}
}
}You said: hello
4 + 9 = 13
Goodbye!
(stopping)
matches! is a handy macro that returns true if a value fits a pattern.
if let: when you care about one variant
If you only want to react to one variant and ignore the rest, if let is shorter than a full match:
enum Event {
KeyPress(char),
Click { x: i32, y: i32 },
Resize,
}
fn main() {
let events = [Event::Resize, Event::KeyPress('q'), Event::Click { x: 10, y: 20 }];
for e in &events {
if let Event::KeyPress(c) = e {
println!("Key pressed: {}", c);
} else if let Event::Click { x, y } = e {
println!("Clicked at ({}, {})", x, y);
} else {
println!("Some other event");
}
}
}Some other event
Key pressed: q
Clicked at (10, 20)
Enums you already know
The standard library is full of enums. The two most important ones are Option<T> (a value that may be missing: Some(v) or None) and Result<T, E> (success Ok(v) or failure Err(e)). They get their own lesson next.
Tip: Whenever you catch yourself using strings or numbers like
"admin","guest"or0, 1, 2to mean "kind of thing", consider an enum. Typos become compile errors instead of bugs.
Test yourself
How do you refer to the Red variant of an enum named Color?
- Color.Red
- Color::Red
- Red::Color
- Color[Red]
What happens if a match on an enum does not handle every variant?
- The missing variants are ignored
- It panics at runtime
- The program does not compile
- It returns None
Which statement about enum variants is true?
- All variants must hold the same data type
- Variants can hold no data, tuple-like data or named fields
- Variants cannot hold data
- Only one variant may hold data