Hone logo
Hone
Problems

Struct Methods for Geometric Shapes

This challenge focuses on defining and utilizing methods within Go structs. You'll be creating structs to represent geometric shapes (Circle and Rectangle) and implementing methods to calculate their areas and perimeters. This exercise reinforces understanding of object-oriented principles in Go and how to encapsulate behavior within data structures.

Problem Description

You are tasked with creating two structs, Circle and Rectangle, in Go. Each struct should have fields representing its dimensions (radius for Circle, width and height for Rectangle). You must then define methods for each struct to calculate and return the area and perimeter of the respective shape. The methods should be named Area() and Perimeter() and should return float64 values. Ensure your calculations are accurate and handle potential edge cases gracefully (e.g., negative dimensions should result in an area/perimeter of 0).

Examples

Example 1:

Input: Circle{Radius: 5.0}
Output: Area: 78.53981633974483, Perimeter: 31.41592653589793
Explanation: Area of a circle is πr², Perimeter is 2πr.  Using π ≈ 3.14159.

Example 2:

Input: Rectangle{Width: 4.0, Height: 6.0}
Output: Area: 24, Perimeter: 20
Explanation: Area of a rectangle is width * height, Perimeter is 2 * (width + height).

Example 3:

Input: Rectangle{Width: -2.0, Height: 5.0}
Output: Area: 0, Perimeter: 0
Explanation: Negative width should result in an area and perimeter of 0.

Constraints

  • The Radius of the Circle struct will be a float64 and can be positive, negative, or zero.
  • The Width and Height of the Rectangle struct will be float64 and can be positive, negative, or zero.
  • The area and perimeter calculations must be accurate to at least two decimal places.
  • The Area() and Perimeter() methods must be defined as receiver methods on the respective structs.
  • Use math.Pi for the value of Pi.

Notes

  • Remember that methods are associated with a specific type (struct in this case).
  • Consider using math.Abs() to handle negative dimensions gracefully when calculating area and perimeter.
  • The return types of Area() and Perimeter() are float64.
  • Focus on clear, concise, and readable code. Good variable names are encouraged.
  • The challenge is to demonstrate your understanding of struct methods and basic geometric calculations.
Loading editor...
go