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 1 / 2

Give Rect a new constructor and an area method.

Hints
  • Methods live in impl Rect { fn area(&self) -> u32 { ... } }.
  • Self inside an impl block means the type itself.
06_structs_enums.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
struct Rect { w: u32, h: u32 }

impl Rect {
    fn new(w: u32, h: u32) -> Self {
        Rect { w, h }
    }
    fn area(&self) -> u32 {
        self.w * self.h
    }
}