Start learning free

LESSON 608 OF 639 · OBJECT-ORIENTED PROGRAMMING

Shape Area in Go

Practice

You write the common part of three shapes, and each shape's area.

Go has no abstract classes. As in the abstract-classes lesson, an interface plays that role. The interface Shape lists two methods:

  • area() int returns the shape's area.
  • name() string returns the shape's name.

Go interfaces have no method bodies. So the shared part is a function, describe(s Shape). It returns a text such as Square with area 25. That is the name, then with area, then the area.

Three structs are shapes:

  • NewRectangle(width, height) builds a Rectangle. Its area is width × height.
  • NewSquare(side) builds a Square. Its area is side × side.
  • NewRightTriangle(a, b) builds a RightTriangle. Its sides a and b meet at a right angle. Its area is a × b / 2, rounded down.

Their constructors and name() methods are already written. You write each area().

For each shape, the harness prints describe(shape) on its own line.

 

Example 1:

Input: NewRectangle(3, 4), NewSquare(5), NewRightTriangle(3, 4)
Output:
Rectangle with area 12
Square with area 25
Right triangle with area 6

Explanation: 3 × 4 = 12 and 5 × 5 = 25.
The triangle is half of 3 × 4, so 6.

Example 2:

Input: NewRightTriangle(3, 5), NewSquare(1)
Output:
Right triangle with area 7
Square with area 1

Explanation: Half of 3 × 5 is 7.5.
It rounds down to 7.

Example 3:

Input: NewRectangle(1, 7), NewRightTriangle(1, 1)
Output:
Rectangle with area 7
Right triangle with area 0

Explanation: A 1 by 7 rectangle has area 7.
Half of 1 × 1 rounds down to 0.

 

Constraints:

  • 1 to 100 shapes.
  • Each size is a whole number from 1 to 10,000.
STEP 1 OF 6
    Ctrl + Enter to check

    Shape Area in Go

    Keep going with Go500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free