Sub topic 1
Defining enums and variants
An enum (short for enumeration) is a type whose values are exactly one of a fixed list of named options. Each option is a variant. This chapter covers how to declare an enum, create its values, give it useful traits, and avoid the errors that come up first. Later chapters cover how variants carry data in detail, and how match takes them apart.
Prerequisites
This chapter assumes you can do the following:
- Write basic Rust: variables, functions,
if, and loops. - Define and use structs and tuples.
- Explain what a move and a borrow are, at the level of "assigning a
Stringmoves it". - Build and run a small program with
cargo run.
Why enums exist
Suppose an account can be active, suspended, or closed. You could store this as a u8 where 0, 1, and 2 stand for the states. Nothing stops a caller from passing 7. You could also use two bool fields, but then is_closed: false, is_suspended: true and is_closed: true, is_suspended: true both look legal, and one of them probably means nothing.
An enum states the options once and makes the compiler enforce them:
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
fn main() {
let heading = Direction::North;
println!("{:?}", heading);
}This prints North. The pieces are:
enum Directiondeclares a new type namedDirection.North,East,South, andWestare its variants. By convention, both the type name and the variant names useUpperCamelCase.Direction::Northis a value of typeDirection. The::is the path separator. Variants live inside the enum's namespace, soNorthalone is not in scope.#[derive(Debug)]asks the compiler to generate theDebugtrait, which{:?}needs for printing.
A variant is not a type of its own. Direction::North has type Direction, so you cannot write fn turn(d: Direction::North). A function that accepts any direction takes a Direction.
Three shapes of variant
Variants come in three forms, and one enum can mix them.
| Form | Declaration | Creating a value |
|---|---|---|
| Unit variant | `Tick` | `Event::Tick` |
| Tuple variant | `Key(char)` | `Event::Key('a')` |
| Struct-like variant | `Click { x: i32, y: i32 }` | `Event::Click { x: 10, y: 20 }` |
#[derive(Debug)]
enum Event {
Tick,
Key(char),
Click { x: i32, y: i32 },
}
fn main() {
let events = vec![
Event::Tick,
Event::Key('a'),
Event::Click { x: 10, y: 20 },
];
for e in &events {
println!("{e:?}");
}
}The output is:
Tick
Key('a')
Click { x: 10, y: 20 }All three values have the same type, Event, so they fit in one Vec<Event>. This is the main practical difference from a set of unrelated structs. The next chapter looks at the data inside variants. Here, notice that the variant list is the whole definition of the type.
Tuple variants are constructor functions
A tuple variant name works as a function from its fields to the enum. Event::Key has the type fn(char) -> Event, so you can pass it wherever a function is expected:
#[derive(Debug)]
enum Event {
Tick,
Key(char),
}
fn main() {
let mut events: Vec<Event> = "hi".chars().map(Event::Key).collect();
events.push(Event::Tick);
println!("{events:?}");
}This prints [Key('h'), Key('i'), Tick]. Struct-like variants do not work this way, so you cannot pass Event::Click to map.
Enums as struct fields
Enums are ordinary types. They can be struct fields, function parameters, and return values:
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Status {
Active,
Suspended,
Closed,
}
struct Account {
id: u32,
status: Status,
}
fn can_withdraw(account: &Account) -> bool {
account.status == Status::Active
}
fn main() {
let mut account = Account { id: 7, status: Status::Active };
println!("{} {:?} {}", account.id, account.status, can_withdraw(&account));
account.status = Status::Suspended;
println!("{} {:?} {}", account.id, account.status, can_withdraw(&account));
}The output is:
7 Active true
7 Suspended falseThree derives matter here:
PartialEqprovides==and!=. Without it,account.status == Status::Activedoes not compile.CloneandCopymake the enum copy on assignment, like an integer. This is only allowed when every field in every variant is itselfCopy. A plain list of unit variants always qualifies.Eqmarks that equality is total. It is a marker with no extra code, and it is needed if you want to use the enum as aHashMapkey, together withHash.
A Copy enum saves you from writing & or .clone() everywhere. Without Copy, passing account.status by value would move it.
Derives that depend on variant order
Two derives use the order in which you wrote the variants:
PartialOrdandOrdcompare variants by position, first to last.Defaultneeds you to mark one unit variant with#[default].
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Priority {
Low,
#[default]
Normal,
High,
}
fn main() {
let p = Priority::default();
println!("{:?}", p);
println!("{}", Priority::High > Priority::Low);
let mut all = [Priority::High, Priority::Low, Priority::Normal];
all.sort();
println!("{:?}", all);
}The output is:
Normal
true
[Low, Normal, High]Reordering the variants changes every comparison and every sort result. If the order is part of your program's meaning, say so in a comment. A harmless-looking edit can otherwise change behavior.
Bringing variants into scope
Writing Direction:: every time can be noisy. A use declaration imports variants by name:
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
fn opposite_label(d: &Direction) -> &'static str {
use Direction::*;
if matches!(d, North) { "south" }
else if matches!(d, South) { "north" }
else if matches!(d, East) { "west" }
else { "east" }
}
fn main() {
println!("{}", opposite_label(&Direction::East));
let _ = Direction::West;
}This prints west. (matches! is covered in a later chapter. Here it just tests whether a value is a given variant.) Placing use Direction::*; inside a function limits the import to that function. A glob import at the top of a file is easy to misuse. If you misspell a variant name in a later pattern, the compiler may treat the misspelling as a new variable name instead of reporting an error. Prefer importing inside a small scope, or import specific names: use Direction::{North, South};.
Size and layout
An enum value stores a tag (which variant it is) plus room for the largest variant's data. For an enum with only unit variants, the tag is all there is, so Direction takes one byte:
use std::mem::size_of;
#[allow(dead_code)]
enum Direction {
North,
East,
South,
West,
}
#[allow(dead_code)]
enum Event {
Tick,
Key(char),
Click { x: i32, y: i32 },
}
fn main() {
println!("Direction: {} byte(s)", size_of::<Direction>());
println!("Event: {} byte(s)", size_of::<Event>());
}Direction prints 1. The Event size depends on the compiler and platform, but it is at least as large as the biggest variant (Click, 8 bytes) plus the tag. One large variant makes every value of the enum large, which matters if you store millions of them. A common fix is to put a big payload behind a Box, covered in a later chapter.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `cannot find value 'North' in this scope` | The variant was used without its enum path | Write `Direction::North` or add a `use` |
| ``` `Direction` doesn't implement `Debug` ``` | `{:?}` was used without the derive | Add `#[derive(Debug)]` |
| ``` binary operation `==` cannot be applied to type `Status` ``` | Missing `PartialEq` | Add `#[derive(PartialEq)]` |
| `use of moved value` after passing an enum | The enum is not `Copy` | Derive `Clone, Copy` if all fields allow it, or borrow with `&` |
| `the trait bound ... Copy is not satisfied` on derive | A variant holds a `String` or other non-`Copy` type | Remove `Copy`, or change the field type |
| `no default declared` when deriving `Default` | No variant is marked `#[default]` | Add `#[default]` to one unit variant |
Exercise
Define an enum Light with variants Red, Yellow, and Green. Derive the traits needed so that Light::Red == Light::Red compiles, the value can be printed with {:?}, and a Light can be assigned to a second variable without the first becoming unusable. Which traits did you derive?
Show answer
#[derive(Debug, Clone, Copy, PartialEq)]. Debug enables {:?}, PartialEq enables ==, and Copy (which requires Clone) makes assignment copy the value instead of moving it. Adding Eq is also valid.
Exercise
Given enum Shape { Dot, Circle(f64), Rect { w: f64, h: f64 } }, write the expressions that create one value of each variant, and write a line that turns the Vec<f64> [1.0, 2.0] into a Vec<Shape> of circles using a variant name as a function.
Show answer
Shape::Dot, Shape::Circle(1.5), and Shape::Rect { w: 2.0, h: 3.0 } create the three variants. For the conversion, let circles: Vec<Shape> = vec![1.0, 2.0].into_iter().map(Shape::Circle).collect(); works because the tuple variant Shape::Circle has type fn(f64) -> Shape. Shape::Rect cannot be used this way because it is struct-like.