Sub topic 1
Defining enums and variants
An enum is a type whose values are exactly one of a fixed set of named alternatives. Each alternative is called a variant. This chapter covers how to declare an enum, create its values, and use it as a type. Later chapters add data to variants and take values apart with match.
Prerequisites
This chapter assumes you can:
- Write and call functions, and use
letbindings. - Define a struct and read its fields.
- Run a small program with
cargo run.
Declaring an enum
An enum declaration lists its variants inside braces, separated by commas. Variants with no data attached are called unit variants.
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
fn main() {
let heading = Direction::North;
println!("{:?}", heading);
}This prints North. The #[derive(Debug)] line asks the compiler to generate the code that {:?} needs to print the value. Without it, the println! call does not compile.
By convention, enum and variant names use UpperCamelCase.
Variants live inside the enum's namespace
You reach a variant through the enum's name and a double colon: Direction::North. Two enums can therefore both have a variant called North without a clash.
enum Compass {
North,
}
enum Ship {
North,
}If the prefix gets noisy, a use declaration brings variants into scope.
#[derive(Debug)]
enum Direction {
North,
East,
South,
West,
}
use Direction::{East, West};
fn main() {
let a = East;
let b = West;
println!("{:?} {:?}", a, b);
}You can also write use Direction::*; to import every variant. Be careful with it. A misspelled name in a pattern can be read as a new variable instead of a variant, which causes bugs that are hard to see.
An enum is a single type
All variants share the type of their enum. Direction::North and Direction::West are both Direction, so one function signature accepts any of them.
#[derive(Debug, Clone, Copy)]
enum Direction {
North,
East,
South,
West,
}
fn turn_right(d: Direction) -> Direction {
match d {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
fn main() {
let mut heading = Direction::North;
for _ in 0..5 {
heading = turn_right(heading);
}
println!("{:?}", heading);
}The match here is previewed only. The next chapters explain it in detail. The program prints East. Clone and Copy let heading be passed by value and used again, as with an integer.
Why not strings or integers?
A &str such as "north" accepts any text, including typos like "nrth". An integer such as 0 forces readers to remember what the number means. An enum makes the compiler reject any value outside the list. It also gives you a name for each case, so a reader sees Direction::North instead of a magic value.
A bool is the same idea with two cases. An enum lets you name the cases and have more than two.
Exercise
Declare an enum Light with the variants Red, Yellow and Green. What do you need to add so that println!("{:?}", Light::Red) compiles, and what does it print?
Show answer
Add #[derive(Debug)] above the enum. The program then prints Red. Without the derive, the compiler reports that Light does not implement Debug.