Introduction
Step 1: Defining an Enum
enum TrafficLight {
Red,
Yellow,
Green,
}
Step 2: Creating Enum Instances
let light = TrafficLight::Red;
Step 3: Using Pattern Matching with Enums
fn traffic_light_duration(light: TrafficLight) -> u32 {
match light {
TrafficLight::Red => 60,
TrafficLight::Yellow => 10,
TrafficLight::Green => 30,
}
}
Step 4: Displaying the Result
fn main() {
let light = TrafficLight::Yellow;
let duration = traffic_light_duration(light);
println!("The duration of the yellow light is {} seconds.", duration);
}
Output:
The duration of the yellow light is 10 seconds.
Conclusion
Great job! You’ve learned how to use enums and pattern matching in Rust. Enums are a helpful way to represent a set of named values, and pattern matching is a powerful tool for handling different cases. Keep exploring intermediate programming concepts and continue learning! 🎉