Defining the Interface
We begin by defining an interface namedshape. This interface requires any implementing type to provide two methods: area and perimeter. Both methods must return a value of type float64, ensuring a consistent design across all shapes.
shape interface.
Implementing the Interface with a Square
Next, we demonstrate how to implement theshape interface using a square struct. The struct includes a single field, side, and implements the required area and perimeter methods. Notice how the method signatures exactly match those defined in the interface, ensuring proper implementation.
The
square type implements the shape interface by providing both the area and perimeter methods, which is a fundamental requirement in Golang for interface satisfaction.Implementing the Interface with a Rectangle
Similarly, you can implement the same interface with arect struct designed for rectangles. This struct introduces two fields: length and breadth. The corresponding area and perimeter methods are implemented in a way that adheres perfectly to the interface’s contract.
rect struct fulfill the exact signatures required by the shape interface, reinforcing the importance of consistency when working with interfaces.
Using the Interface
To illustrate the power of interfaces, we define a function calledprintData that accepts any type conforming to the shape interface. This function prints the area and perimeter for whichever shape is passed to it. In the main function, instances of both rect and square are created and passed to printData, demonstrating how a single function can seamlessly handle different types.
printData function correctly manages both the rectangle and square types. This flexibility highlights the immense power of using interfaces in your Golang applications.
Summary of the Implementation
| Component | Description | Code Snippet |
|---|---|---|
| Interface | Declares the shape interface with area and perimeter cut. | (See code in “Defining the Interface” section) |
| Square Implementation | Implements the interface with a single side attribute. | (See code in “Implementing the Interface with a Square” section) |
| Rectangle Implementation | Uses length and breadth to fulfill the interface contract. | (See code in “Implementing the Interface with a Rectangle” section) |
| Function Usage | Demonstrates how to dynamically apply the method for any shape. | (See code in “Using the Interface” section) |