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.
Give Rect a new constructor and an area method.
Hints
- Methods live in
impl Rect { fn area(&self) -> u32 { ... } }. Selfinside an impl block means the type itself.
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
}
}