Rust Enums and Pattern Matching
Master enums with embedded data, exhaustively match patterns with the match expression, handle null safety with Option, and use if let.
Eighth post in the basic Rust series. Enums allow you to define a type by enumerating its possible variants. Combined with pattern matching, Rust enums provide expressive control flow and type-safe state representation.
Defining enums with data#
Unlike C-style enums, Rust enums can store data inside each variant:
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn main() {
let msg1 = Message::Write(String::from("hello"));
let msg2 = Message::Move { x: 10, y: 20 };
}rustPattern matching with match#
The match expression inspects an enum variant and extracts its inner data. Matches in Rust are exhaustive — every possible variant must be handled:
fn process(msg: Message) {
match msg {
Message::Quit => println!("Quit signal received"),
Message::Move { x, y } => println!("Move to ({x}, {y})"),
Message::Write(text) => println!("Text message: {text}"),
Message::ChangeColor(r, g, b) => println!("Change color to ({r}, {g}, {b})"),
}
}rustThe Option enum: replacing null#
Rust does not have null. Instead, the standard library defines the Option<T> enum to encode the presence or absence of a value:
enum Option<T> {
Some(T),
None,
}rustBecause Option<T> and T are different types, the compiler forces you to handle the None case before accessing T:
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let absent = plus_one(None);rustConcise matching with if let#
When you only care about matching one specific variant and ignoring the rest, use if let:
let config_max = Some(8u8);
if let Some(max) = config_max {
println!("The maximum is configured to be {max}");
}rustConclusion#
Enums represent data that can be one of several possibilities, match ensures all cases are handled safely, and Option eliminates null-pointer exceptions. Next in this series: collections (Vec, String, HashMap).