Start learning free

LESSON 42 OF 69 · OBJECT-ORIENTED PROGRAMMING

Shape Area in Go: An Interface and a Shared Function

Practice Read the full explanation

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

    GO · OBJECT-ORIENTED PROGRAMMING

    Shape Area in Go, explained

    Problem overview

    You work with three shapes: a rectangle, a square and a right triangle. Each can report its area() and its name(), and one function, describe(s Shape), turns any shape into a sentence such as Square with area 25. The constructors and name() methods are already written. You write the interface, describe and the three area methods.

    ShapeArea
    Rectanglewidth times height
    Squareside times side
    RightTrianglea times b divided by 2, rounded down

    For NewRightTriangle(3, 5) the exact half is 7.5, and the lesson's answer is 7.

    Approach

    Other languages put the shared code in an abstract class: a parent with some methods written and some left blank for the children. Go has no classes, so the roles split in two:

    • the interface lists what every shape must have: area() int and name() string. It has signatures only, never bodies;
    • the shared code is an ordinary function that takes the interface, so it works for any shape.

    Each struct becomes a Shape just by having both methods, with no extra declaration. Since the constructors and name() are given, your work is the interface, the function and three small formulas.

    Step by step

    1. The first method. Inside Shape, write area() int.
    2. The second. Add name() string.
    3. describe. Return s.name(), then " with area ", then the area as text. A string can only be joined to a string, so the integer goes through strconv.Itoa.
    4. Rectangle. Return this.width * this.height.
    5. Square. Return this.side * this.side.
    6. Right triangle. Return this.a * this.b / 2. It is half of an a by b rectangle.

    The solution in Go

    type Shape interface {
        area() int
        name() string
    }
    
    func describe(s Shape) string {
        return s.name() + " with area " + strconv.Itoa(s.area())
    }
    
    type Rectangle struct {
        width int
        height int
    }
    
    func NewRectangle(width int, height int) Rectangle {
        return Rectangle{width: width, height: height}
    }
    
    func (this Rectangle) name() string {
        return "Rectangle"
    }
    
    func (this Rectangle) area() int {
        return this.width * this.height
    }
    
    type Square struct {
        side int
    }
    
    func NewSquare(side int) Square {
        return Square{side: side}
    }
    
    func (this Square) name() string {
        return "Square"
    }
    
    func (this Square) area() int {
        return this.side * this.side
    }
    
    type RightTriangle struct {
        a int
        b int
    }
    
    func NewRightTriangle(a int, b int) RightTriangle {
        return RightTriangle{a: a, b: b}
    }
    
    func (this RightTriangle) name() string {
        return "Right triangle"
    }
    
    func (this RightTriangle) area() int {
        return this.a * this.b / 2
    }
    

    Language details

    Integer division. Both operands of this.a * this.b / 2 are int, so Go divides as integers and drops the fraction, rounding toward zero. For positive sizes that is rounding down. With a = 3 and b = 5, the expression is 15 / 2, which is 7. Converting to float64 would give 7.5, which is not what the lesson wants.

    Number to text. strconv.Itoa(25) returns "25". Converting with string(n) is different: it reads the number as a character code, so string(rune(68)) is "D". Use Itoa to print a number.

    The shared function. describe calls s.name() and s.area() and nothing else, so it works for the three shapes and for any shape added later.

    Why describe is a function

    In a language with abstract classes, describe would be a method of the parent that the children inherit. A Go interface can't hold code, and embedding is not the right tool here, because a rectangle and a triangle have nothing in common to embed. A plain function that accepts the interface does the same job with less machinery: the text is built in one place, and the name and area come from whichever shape is passed in.

    The order of the pieces also matters. describe joins three parts: the name, the fixed words " with area " and the area. If you drop the spaces around with, the text no longer matches what the tests expect, and they fail.

    Adding a fourth shape

    To add a circle or a trapezoid, you would write a struct with a constructor, a name() and an area(). Neither the interface nor describe would change. That is the payoff of the design: the shared code depends only on the two methods in the interface, not on any particular shape.

    Complexity

    Each area() is one multiplication and at most one division, so it takes constant time, and describe builds a short string. Describing n shapes takes O(n) in total.

    Testing

    Passing each shape to describe and printing the result gives:

    NewRectangle(3, 4)       Rectangle with area 12
    NewSquare(5)             Square with area 25
    NewRightTriangle(3, 4)   Right triangle with area 6
    NewRightTriangle(3, 5)   Right triangle with area 7
    NewSquare(1)             Square with area 1
    NewRectangle(1, 7)       Rectangle with area 7
    NewRightTriangle(1, 1)   Right triangle with area 0
    

    The last row shows the rounding at its sharpest: half of 1 is 0.5, which becomes 0.

    Sizes go up to 10,000, and the largest area is 10,000 times 10,000, which is 100,000,000 for a rectangle or a square. A 64-bit int holds that easily.

    Another way to see the interface: it is a promise about what a caller may do. describe may call area and name on whatever it is given, and it may do nothing else, such as read width. That limit is what lets one function serve all three shapes.

    Edge cases and common mistakes

    • Dividing first. this.a / 2 * this.b gives a different answer when a is odd: for 3 and 5 it gives 5, not 7 (3 / 2 is already 1). Multiply first, then divide.
    • Method names that don't match. A struct whose method is spelled differently, Area for example, does not satisfy the interface, and passing it to describe is a compile error.
    • Joining text and a number. "area " + s.area() doesn't compile, because one side is a string and the other an int.
    • Putting a body in the interface. Interfaces list signatures only. The shared part is the function.
    Keep going with Go1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free