Rust — Enums
Basic enum
enum Direction {
North,
South,
East,
West,
}
fn main() {
let dir = Direction::North;
match dir {
Direction::North => println!("North"),
Direction::South => println!("South"),
Direction::East => println!("East"),
Direction::West => println!("West"),
}
}
Enums with data
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
fn process(msg: Message) {
match msg {
Message::Quit => println!("Quit"),
Message::Move { x, y } => println!("Move to ({}, {})", x, y),
Message::Write(text) => println!("Write: {}", text),
Message::ChangeColor(r, g, b) => println!("Color: ({}, {}, {})", r, g, b),
}
}
Option<T>
fn divide(a: f64, b: f64) -> Option<f64> {
if b == 0.0 {
None
} else {
Some(a / b)
}
}
fn main() {
match divide(10.0, 3.0) {
Some(result) => println!("Result: {:.2}", result),
None => println!("Cannot divide by zero"),
}
}
Methods on enums
enum TrafficLight {
Red,
Yellow,
Green,
}
impl TrafficLight {
fn duration(&self) -> u32 {
match self {
TrafficLight::Red => 60,
TrafficLight::Yellow => 5,
TrafficLight::Green => 45,
}
}
}
fn main() {
let light = TrafficLight::Red;
println!("Duration: {}s", light.duration());
}
if let
fn main() {
let some_value: Option<i32> = Some(42);
if let Some(value) = some_value {
println!("Got: {}", value);
}
}
Mini Practice
Write Rust code that:
- Creates an enum with data variants
- Uses pattern matching with
match - Works with
Option<T> - Implements methods on an enum
Up Next
In the next lesson, you'll learn about Traits — defining shared behavior.
Related Topics
Frequently Asked Questions about Enums
What is Enums in Rust?
Enums is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Enums?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Enums.
Why is Enums important in Rust?
Enums is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.