Menu
Coddy logo textTech

Recap - Shape Calculator

Part of the Object Oriented Programming section of Coddy's GO journey — lesson 33 of 107.

challenge icon

Challenge

Easy

Let's build a shape calculator that brings together all the interface concepts from this chapter. You'll create a system where different geometric shapes can be processed uniformly through a shared interface, demonstrating the power of polymorphism in Go.

You'll organize your code across three files:

  • shape.go: Define a Shape interface with two methods: Area() float64 and Perimeter() float64. Also create a function called DescribeShape that accepts any Shape and returns a formatted string showing both its area and perimeter.
  • shapes.go: Create two structs that implement the Shape interface:
    • A Rectangle with Width and Height fields
    • A Circle with a Radius field
    Each struct should implement both Area() and Perimeter() methods, plus a String() method (implementing fmt.Stringer) that returns a readable description of the shape.
  • main.go: Read shape data from input, create the appropriate shapes, and use your DescribeShape function to display information about each one. Also print each shape directly to demonstrate the Stringer interface.

The following inputs will be provided:

  • Line 1: Rectangle width (float)
  • Line 2: Rectangle height (float)
  • Line 3: Circle radius (float)

For calculations, use 3.14159 as the value of pi. Circle perimeter is 2 * pi * radius.

Your String() methods should return:

  • Rectangle: Rectangle(Width x Height)
  • Circle: Circle(Radius: R)

Your DescribeShape function should return:

Area: [area], Perimeter: [perimeter]

Format all float values with two decimal places using %.2f.

For example, given 4, 3, and 5, your output should be:

Rectangle(4.00 x 3.00)
Area: 12.00, Perimeter: 14.00
Circle(Radius: 5.00)
Area: 78.54, Perimeter: 31.42

Print each shape first (using its String() method), then its description from DescribeShape. Process the rectangle first, then the circle.

Try it yourself

package main

import (
	"fmt"
)

func main() {
	// Read input values
	var width, height, radius float64
	fmt.Scanln(&width)
	fmt.Scanln(&height)
	fmt.Scanln(&radius)

	// TODO: Create a Rectangle with the given width and height

	// TODO: Create a Circle with the given radius

	// TODO: Print the rectangle (uses String() method)
	// TODO: Print the rectangle's description using DescribeShape()

	// TODO: Print the circle (uses String() method)
	// TODO: Print the circle's description using DescribeShape()
}

All lessons in Object Oriented Programming