Skip to content

Pattern matching

Let you pattern match across various variants of an enum and run some logic

// Define an enum called Shape
enum Shape {
Circle(f64), // Variant with associated data (radius)
Square(f64), // Variant with associated data (side length)
Rectangle(f64, f64), // Variant with associated data (width, height)
}
// Function to calculate area based on the shape
fn calculate_area(shape: Shape) -> f64 {
match shape {
Shape::Circle(radius) => std::f64::consts::PI * radius * radius,
Shape::Square(side_length) => side_length * side_length,
Shape::Rectangle(width, height) => width * height,
}
}
fn main() {
// Create instances of different shapes
let circle = Shape::Circle(5.0);
let square = Shape::Square(4.0);
let rectangle = Shape::Rectangle(3.0, 6.0);
// Calculate and print the areas
println!("Area of circle: {}", calculate_area(circle));
println!("Area of square: {}", calculate_area(square));
println!("Area of rectangle: {}", calculate_area(rectangle));
}