Core Beginner
06 Structs & enums
Give a Rect a constructor and an area method, then compute the area of an enum that holds different data per variant.
Compute the area of each Shape variant in shape_area.
Hints
- enum variants can carry data;
matchto pull it out.
Reveal solution
enum Shape { Circle(f64), Square(f64) }
fn shape_area(s: &Shape) -> f64 {
match s {
Shape::Circle(r) => std::f64::consts::PI * r * r,
Shape::Square(side) => side * side,
}
}