Skip to content
Exercise · Interfaces · lesson 9 of 10

Exercise: total area

The Shape interface with the method Area() float64 and the types Rect and Circle that implement it are already declared. Write a function func totalArea(shapes []Shape) float64 that returns the sum of the areas of all shapes in the slice — of any type that implements Shape, not only Rect and Circle.

  • r := Rect{Width: 2, Height: 3}, sq := Rect{Width: 1, Height: 1}, then totalArea([]Shape{r, sq}) → 7
  • c := Circle{Radius: 1}, then totalArea([]Shape{c}) → 3.141592653589793
  • totalArea(nil) → 0

Constraints: the same shape may appear in the slice several times and counts each time; the slice may be empty or nil, and then the sum is 0; the result is compared with a tolerance of 1e-9.

Do not add extra imports unless the task says so explicitly.

area.go — go
go · 28 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