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
Shapeinterface with theArea()method. - Create
RectangleandCirclestructs. - Implement the
Area()method for bothRectangleandCirclestructs. - Create a
PrintAreafunction that accepts aShapeinterface and prints the area. - Demonstrate the usage of the
PrintAreafunction with both aRectangleand aCircle.
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 afloat64. - The
Rectanglestruct must havewidthandheightfields of typefloat64. - The
Circlestruct must have aradiusfield of typefloat64. - The
PrintAreafunction should print the area to the console usingfmt.Println. - Use the
mathpackage 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
PrintAreafunction. - Focus on the core concepts of interface definition and implementation. Error handling and input validation are not the primary focus of this challenge.