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:
- Define a
Circlestruct with aRadiusfield. - Define a
Rectanglestruct withWidthandHeightfields. - Implement an
Area()method forCirclethat calculates its area (π * radius²). - Implement a
Perimeter()method forCirclethat calculates its circumference (2 * π * radius). - Implement an
Area()method forRectanglethat calculates its area (width * height). - Implement a
Perimeter()method forRectanglethat 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.Pifrom the Go standard library for precision. - The methods should return
float64values for area and perimeter.
Notes
- You will need to import the
mathpackage formath.Pi. - Consider how to access the struct fields within your methods.
- You can define multiple methods for a single struct.