Implementing Interface Satisfaction in Go
This challenge focuses on understanding and implementing interface satisfaction in Go. Interfaces define a set of methods, and any type that implements all those methods satisfies the interface, even if it's not explicitly declared. This is a core concept in Go's flexibility and polymorphism.
Problem Description
You are tasked with creating a system for handling different types of Shapes. You'll define an interface Shape with a method Area() that returns the area of the shape as a float64. You need to implement two concrete types, Circle and Rectangle, both of which satisfy the Shape interface. Finally, you'll write a function PrintArea(shape Shape) that takes a Shape as input and prints its area to the console.
Key Requirements:
- Define an interface
Shapewith a methodArea() float64. - Implement the
Shapeinterface for bothCircleandRectangletypes. Circleshould have aRadiusfield (float64).Rectangleshould haveWidthandHeightfields (both float64).- The
Area()method forCircleshould calculate the area of a circle (π * radius^2). - The
Area()method forRectangleshould calculate the area of a rectangle (width * height). - The
PrintAreafunction should accept any type that satisfies theShapeinterface and print the area returned by itsArea()method. - Handle potential errors gracefully (though error handling isn't explicitly required for the area calculations themselves, consider how you might handle invalid input in a real-world scenario).
Expected Behavior:
The program should correctly calculate and print the area of both a Circle and a Rectangle when passed to the PrintArea function. The output should be formatted as "Area: [area_value]".
Edge Cases to Consider:
- Zero radius for a circle.
- Zero width or height for a rectangle.
- While not required, consider how you might handle negative values for dimensions (e.g., by returning an error or treating them as zero).
Examples
Example 1:
Input: Circle{Radius: 5.0}
Output: Area: 78.53981633974483
Explanation: The area of a circle with radius 5.0 is π * 5.0^2 ≈ 78.54.
Example 2:
Input: Rectangle{Width: 4.0, Height: 6.0}
Output: Area: 24
Explanation: The area of a rectangle with width 4.0 and height 6.0 is 4.0 * 6.0 = 24.
Example 3: (Edge Case)
Input: Circle{Radius: 0.0}
Output: Area: 0
Explanation: The area of a circle with radius 0.0 is 0.
Constraints
- The
Area()method must return afloat64. - The
PrintAreafunction must accept aShapeinterface as input. - The program should be well-structured and readable.
- No external libraries are allowed.
- The radius, width, and height values will be non-negative.
Notes
- Remember that Go interfaces are satisfied implicitly. You don't need to explicitly declare that a type implements an interface.
- Focus on demonstrating your understanding of interface satisfaction and polymorphism.
- Consider using
fmt.Printffor formatted output. - Think about how you might extend this system to support other shapes in the future.