In this tutorial, you’ll learn how to define enums and use them with pattern matching.
What is an Enum? #
An enum (short for enumeration) is a type that can be one of several variants.
Think of it as a way to express “this OR that” in your data model. For Example:
enum Direction {
Up,
Down,
Left,
Right,
}
fn main() {
let go = Direction::Up;
match go {
Direction::Up => println!("Moving up!"),
Direction::Down => println!("Moving down!"),
Direction::Left => println!("Going left!"),
Direction::Right => println!("Going right!"),
}
}
Code language: Rust (rust)In this example:
- Each variant is part of the
Directiontype. - Pattern matching (
match) makes sure we handle all cases at compile time.
Enums with Data #
Variants can carry extra data, just like tuples or structs.
enum Message {
Quit, // no data
Move { x: i32, y: i32 }, // struct-like
Write(String), // tuple-like
ChangeColor(i32, i32, i32) // tuple-like
}
fn main() {
let msgs = [
Message::Quit,
Message::Move { x: 10, y: 20 },
Message::Write(String::from("Hello!")),
Message::ChangeColor(255, 0, 0),
];
for msg in msgs {
match msg {
Message::Quit => println!("Quit message"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Message: {}", text),
Message::ChangeColor(r, g, b) => {
println!("Change color to RGB({}, {}, {})", r, g, b)
}
}
}
}
Code language: Rust (rust)Enums can mix different shapes of data in one type. This makes them more flexible than structs.
The Option Enum #
Rust’s standard library defines an enum called Option<T>:
enum Option<T> {
Some(T),
None,
}
Code language: Rust (rust)Usage:
fn main() {
let some_number = Some(42);
let no_number: Option<i32> = None;
match some_number {
Some(n) => println!("Got number: {}", n),
None => println!("No number found"),
}
}
Code language: Rust (rust)Option<T> replaces null values in Rust. The compiler forces you to handle both Some and None, preventing null pointer errors.
Concise Matching with if let #
Sometimes, you only care about one variant. You can use if let:
fn main() {
let config = Some(7);
if let Some(val) = config {
println!("Config value: {}", val);
}
}
Code language: Rust (rust)Shorter than a full match when you only need one branch.
Summary #
- Enums let you define types with multiple possible variants.
- Variants can hold data (like tuples or structs).
- Pattern matching (
match) ensures you handle all possibilities. - Built-in enums like
Option<T>eliminate null-related bugs.