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
By harnessing interfaces in Golang, you create more modular, flexible, and maintainable code.
For deeper understanding, refer to Golang Interfaces.
And that concludes our lesson on implementing interfaces in Golang. Now it’s time to get hands-on practice and further explore these concepts in your applications!