Rust Enums and Pattern Matching — Defining Enums, Options, Results, and Match Patterns
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about Rust Enums and Pattern Matching. We cover key concepts, practical examples, and best practices to help you master this topic.
Rust enums define types with multiple variants using match for exhaustive pattern matching, Option for nullable values, and Result for error handling.
What You'll Learn
- Enum definition and variants
- Match expressions with patterns
- Option and Result enums
- if let and while let
Why It Matters
Enums power Rust's error handling and state modeling. DodaZIP uses Result for file operations. Firefox uses enums for HTTP response statuses.
Real-World Use
State machines, error handling, configuration Parsing, network protocol handling.
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
impl Message {
fn call(&self) {
match self {
Message::Quit => println!("Quitting"),
Message::Move { x, y } => println!("Move to {}, {}", x, y),
Message::Write(text) => println!("Writing: {}", text),
Message::ChangeColor(r, g, b) => println!("Color: {} {} {}", r, g, b),
}
}
}
enum Coin { Penny, Nickel, Dime, Quarter }
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
fn main() {
let msg = Message::Write(String::from("hello"));
msg.call();
let some_number = Some(5);
let absent_number: Option<i32> = None;
if let Some(value) = some_number {
println!("Got: {}", value);
}
let result: Result<i32, &str> = Ok(42);
match result {
Ok(v) => println!("Success: {}", v),
Err(e) => println!("Error: {}", e),
}
}
← Previous
Rust Structs — Defining, Instantiating, and Implementing Methods on Struct Types
Next →
Rust Error Handling — Result, Option, Panic, and Error Propagation with ? Operator
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro