Match with Enums in Rust: A Comprehensive Guide šŸŽÆ

beginner
23 min

Match with Enums in Rust: A Comprehensive Guide šŸŽÆ

Welcome to the exciting world of Rust! Today, we're diving deep into understanding and mastering the match keyword with Enums in Rust. Let's get started! šŸ“

What are Enums? šŸ’”

Enums, or enumerations, are a data type that lets you define a set of possible values. They are particularly useful when you want to define a collection of distinct, related values. In Rust, enums can be marked as tuple, struct or discriminated. Today, we will focus on discriminated enums.

Creating an Enum šŸ“

To create a discriminated enum, you simply define the enum name followed by the keyword enum, and list the possible variants enclosed in curly braces {}.

rust
enum Shape { Circle, Rectangle, Square, }

The match Keyword šŸ’”

The match keyword in Rust allows us to test an expression against multiple patterns, execute code for each match, and handle different variants of our enums.

Basic match Example šŸ“

Here's a simple example where we create a variable of type Shape and use the match keyword to handle each variant.

rust
fn main() { let shape = Shape::Circle; match shape { Shape::Circle => println!("This is a circle!"), Shape::Rectangle => println!("This is a rectangle!"), Shape::Square => println!("This is a square!"), } }

šŸ“ Note: In the example above, if the shape variable holds the Circle variant, the message "This is a circle!" will be printed.

Pattern Matching with Enums šŸ’”

One powerful feature of match is pattern matching. This allows us to extract data from the enum variants.

rust
enum Shape { Circle(f64), Rectangle { width: f64, height: f64 }, Square(f64), } fn main() { let shape = Shape::Circle(5.0); match shape { Shape::Circle(radius) => println!("The circle has a radius of {}", radius), Shape::Rectangle { width, height } => println!("The rectangle has a width of {} and height of {}", width, height), Shape::Square(side) => println!("The square has a side length of {}", side), } }

šŸ“ Note: In the example above, we pattern match against each variant and extract data using destructuring.

Quiz Time šŸŽÆ

Question: What type of enum is Shape in the example?

A: Tuple Enum B: Discriminated Enum C: Struct Enum Correct: B Explanation: The Shape enum in the example is a discriminated enum.


Stay tuned for more in-depth examples, advanced use cases, and a quiz to test your understanding! šŸŽ‰