Introduction

Gal Normal

I've learned about structs, so what's next in intermediate programming concepts?

Geek Curious

How about enums and pattern matching? They're useful concepts in some programming languages!

Gal Excited

Ooh, tell me more! Let's learn!

Geek Smiling

Alright! We'll use Rust as our programming language for this example.

Step 1: Defining an Enum

Gal Eager

First, let's define an enum!

Geek Explaining

Enums are a way to define a custom data type that represents a set of named values. Here's an example:

enum TrafficLight {
    Red,
    Yellow,
    Green,
}

Step 2: Creating Enum Instances

Gal Wondering

Now, how do I create instances of an enum?

Geek Ready

You can create instances like this:

let light = TrafficLight::Red;

Step 3: Using Pattern Matching with Enums

Gal Curious

How do I use pattern matching with enums?

Geek Smiling

Pattern matching allows you to handle different enum values in a clear and concise way. Let's create a function that uses pattern matching with our TrafficLight enum!

fn traffic_light_duration(light: TrafficLight) -> u32 {
    match light {
        TrafficLight::Red => 60,
        TrafficLight::Yellow => 10,
        TrafficLight::Green => 30,
    }
}

Step 4: Displaying the Result

Gal Eager

Time to see the result!

Geek Smiling

Here's an example of how to use the function:

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! 🎉