Hone logo
Hone
Problems

Designing a Shape Interface in Go

This challenge focuses on defining and utilizing interfaces in Go. Interfaces are a powerful tool for achieving polymorphism and abstraction, allowing you to write code that works with different types as long as they satisfy a specific contract. Your task is to define an interface representing different shapes and then create concrete types that implement it.

Problem Description

You are tasked with designing a Shape interface in Go. This interface should define a method called Area() which returns the area of the shape as a float64. You will then need to create two concrete types: Rectangle and Circle, both of which implement the Shape interface. The Rectangle should take width and height as arguments to its constructor, and the Circle should take a radius. Finally, you should create a function PrintArea(shape Shape) that takes a Shape as input and prints its area to the console.

Key Requirements:

  • Define the Shape interface with the Area() method.
  • Create Rectangle and Circle structs.
  • Implement the Area() method for both Rectangle and Circle structs.
  • Create a PrintArea function that accepts a Shape interface and prints the area.
  • Demonstrate the usage of the PrintArea function with both a Rectangle and a Circle.

Expected Behavior:

The Area() method should correctly calculate the area for both shapes. The PrintArea function should print the calculated area to the console in a clear format (e.g., "Rectangle Area: 10.0").

Edge Cases to Consider:

  • While not strictly required for this problem, consider how you might handle invalid input (e.g., negative width/height or radius). For simplicity, you can assume valid positive inputs.

Examples

Example 1:

Input: Rectangle{width: 5.0, height: 4.0}
Output: Rectangle Area: 20.0
Explanation: The Area() method for Rectangle calculates 5.0 * 4.0 = 20.0.

Example 2:

Input: Circle{radius: 3.0}
Output: Circle Area: 28.274333882308138
Explanation: The Area() method for Circle calculates π * (3.0)^2 ≈ 28.27.

Constraints

  • The Area() method must return a float64.
  • The Rectangle struct must have width and height fields of type float64.
  • The Circle struct must have a radius field of type float64.
  • The PrintArea function should print the area to the console using fmt.Println.
  • Use the math package for the value of Pi.

Notes

  • Interfaces in Go are implicitly satisfied. A type implements an interface simply by having all the methods declared in the interface.
  • Think about how the interface allows you to treat different shapes uniformly through the PrintArea function.
  • Focus on the core concepts of interface definition and implementation. Error handling and input validation are not the primary focus of this challenge.
Loading editor...
go