Rust Enums Explained - Variants, Pattern Matching & Option Type | Beginner Tutorial
Video: Rust Enums Explained - Variants, Pattern Matching & Option Type | Beginner Tutorial by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust Enums Explained - Variants, Pattern Matching & Option Type
Rust enums allow you to define a type that can be one of several distinct variants, each optionally holding different data. This tutorial covers creating enums, using pattern matching to handle all variants exhaustively, and safely working with nullable values using Rust’s built-in Option type.
Code
/// Basic enum defining four directions
enum Direction {
North,
South,
East,
West,
}
fn main() {
let dir = Direction::North;
// Match on the enum variants exhaustively
match dir {
Direction::North => println!("Going north!"),
Direction::South => println!("Going south!"),
Direction::East => println!("Going east!"),
Direction::West => println!("Going west!"),
}
/// Enum with variants holding different data types
enum Message {
Quit,
Move { x: i32, y: i32 }, // Named fields like a struct
Write(String), // Single string value
ChangeColor(i32, i32, i32), // Tuple of three integers
}
let msg = Message::Move { x: 10, y: 20 };
// Destructure and handle each variant
match msg {
Message::Quit => println!("Quit message received"),
Message::Move { x, y } => println!("Moving to coordinates: ({}, {})", x, y),
Message::Write(text) => println!("Writing message: {}", text),
Message::ChangeColor(r, g, b) => println!("Changing color to RGB({}, {}, {})", r, g, b),
}
/// Using the built-in Option enum to handle nullable values safely
fn find_index(arr: &[i32], target: i32) -> Option {
for (index, &value) in arr.iter().enumerate() {
if value == target {
return Some(index); // Found the target, return Some(index)
}
}
None // Target not found
}
let numbers = [10, 20, 30, 40];
let search = 30;
match find_index(&numbers, search) {
Some(idx) => println!("Found {} at index {}", search, idx),
None => println!("{} not found in the array", search),
}
// Searching for a value not in the array
match find_index(&numbers, 99) {
Some(idx) => println!("Found 99 at index {}", idx),
None => println!("99 not found in the array"),
}
}
Key Points
- Enums define a type with a fixed set of variants, each variant representing a distinct value or data shape.
- The match expression enforces exhaustive handling of all enum variants at compile time, preventing runtime errors.
- Enum variants can store data, including named fields or tuple-like values, which can be destructured in matches.
- The Option enum (Some and None) is Rust’s way to safely represent nullable or optional values without risking null pointer errors.
- Pattern matching on Option forces explicit handling of both presence and absence of a value, improving code safety.