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! š
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.
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 {}.
enum Shape {
Circle,
Rectangle,
Square,
}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.
Here's a simple example where we create a variable of type Shape and use the match keyword to handle each variant.
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.
One powerful feature of match is pattern matching. This allows us to extract data from the enum variants.
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.
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! š