Enums and Pattern Matching
Represent choices and handle them safely with match.
Learning objectives
- Define enums
- Store data inside enum variants
- Use match to handle each case
Enums
An enum defines a type that can be one of several variants. It is useful for states, commands, options, and results.
Enums with Data
Enum variants can also hold data. This makes enums powerful for modeling real application logic.
Pattern Matching
match helps you handle every possible variant in a clear and complete way.
Example code
enum Payment {
Cash,
Card(String),
Online { provider: String, amount: f64 },
}
fn main() {
let payment = Payment::Card(String::from("Visa"));
match payment {
Payment::Cash => println!("Paid by cash"),
Payment::Card(card_type) => println!("Paid by card: {}", card_type),
Payment::Online { provider, amount } => {
println!("Paid online using {}: {}", provider, amount);
}
}
}
Practice task: Create an enum called TrafficLight with Red, Yellow, and Green variants. Use match to print the action for each light.