Hone logo
Hone
Problems

Mastering Go Struct Methods: Building a Shape Calculator

Go's powerful struct feature allows you to define custom data types. Methods provide a way to associate behavior directly with these custom types. This challenge will help you solidify your understanding of creating and using struct methods in Go to build a practical shape calculator.

Problem Description

You are tasked with creating a simple geometry calculator that can handle different shapes like circles and rectangles. To do this, you'll define structs to represent these shapes and then implement methods on these structs to calculate their area and perimeter. This will demonstrate how methods can encapsulate logic relevant to a specific data structure.

What needs to be achieved:

  1. Define a Circle struct with a Radius field.
  2. Define a Rectangle struct with Width and Height fields.
  3. Implement an Area() method for Circle that calculates its area (π * radius²).
  4. Implement a Perimeter() method for Circle that calculates its circumference (2 * π * radius).
  5. Implement an Area() method for Rectangle that calculates its area (width * height).
  6. Implement a Perimeter() method for Rectangle that calculates its perimeter (2 * (width + height)).

Expected behavior: When you create instances of Circle and Rectangle and call their respective Area() and Perimeter() methods, they should return the correct calculated values.

Edge cases to consider:

  • Shapes with zero dimensions (e.g., radius 0, width 0, height 0).

Examples

Example 1:

Input:
circle := Circle{Radius: 5}
rectangle := Rectangle{Width: 4, Height: 6}

Output:
Circle Area: 78.53981633974483
Circle Perimeter: 31.41592653589793
Rectangle Area: 24
Rectangle Perimeter: 20

Explanation: The Area() and Perimeter() methods are called on the circle and rectangle instances, returning their calculated geometric properties.

Example 2:

Input:
zeroCircle := Circle{Radius: 0}
zeroRectangle := Rectangle{Width: 0, Height: 5}

Output:
Zero Circle Area: 0
Zero Circle Perimeter: 0
Zero Rectangle Area: 0
Zero Rectangle Perimeter: 10

Explanation: Demonstrates that the methods correctly handle shapes with zero dimensions.

Constraints

  • The radius, width, and height will be non-negative floating-point numbers.
  • Calculations involving π should use math.Pi from the Go standard library for precision.
  • The methods should return float64 values for area and perimeter.

Notes

  • You will need to import the math package for math.Pi.
  • Consider how to access the struct fields within your methods.
  • You can define multiple methods for a single struct.
Loading editor...
go