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.

Step 2 / 2

Compute the area of each Shape variant in shape_area.

Hints
  • enum variants can carry data; match to pull it out.
06_structs_enums.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
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,
    }
}