Exercise · Structs and methods · lesson 10 of 11
Exercise: rectangle methods
The type type Rect struct{ Width, Height float64 } is already declared. Write two methods: func (r *Rect) Area() float64 returns the rectangle's area, and func (r *Rect) Scale(k float64) multiplies its width and height by k. Scale changes the rectangle, so it needs a pointer receiver; Area gets one too, so that all of the type's receivers are the same kind.
r := Rect{Width: 2, Height: 3}, thenr.Area()→6r := Rect{Width: 2, Height: 3}, thenr.Scale(2)→ris{4 6}r := Rect{Width: 2, Height: 3}, thenr.Scale(0)→ris{0 0}
Constraints: the sides and k are non-negative; after several calls to Scale, their factors multiply.
Do not add extra imports unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.