Skip to content
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}, then r.Area() → 6
  • r := Rect{Width: 2, Height: 3}, then r.Scale(2) → r is {4 6}
  • r := Rect{Width: 2, Height: 3}, then r.Scale(0) → r is {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.

rect.go — go
go · 11 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way