Implementing Interfaces in Go
Introduction to Interfaces
In Go, an interface is a custom type that specifies a set of method signatures. When other types implement these methods, they are said to implement the interface. Interfaces are a powerful feature in Go as they enable polymorphism and decoupling of code.
Defining an Interface
Let's start by defining a simple interface. Consider an interface Shape
that has a method Area()
:
type Shape interface {
Area() float64
}
This interface specifies that any type that has an Area()
method with no parameters and a return type of float64
is said to implement the Shape
interface.
Implementing the Interface
Let's implement the Shape
interface with two different types: Circle
and Rectangle
.
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
Here, both Circle
and Rectangle
types implement the Shape
interface because they have an Area()
method that matches the method signature specified in the interface.
Using the Interface
Now that we have some types that implement the Shape
interface, we can write a function that works with any type that implements the Shape
interface:
func PrintArea(s Shape) {
fmt.Println("Area:", s.Area())
}
We can now call this function with both Circle
and Rectangle
types:
func main() {
c := Circle{Radius: 5}
r := Rectangle{Width: 10, Height: 5}
PrintArea(c)
PrintArea(r)
}
Area: 78.5
Area: 50
Conclusion
In this tutorial, we learned how to define and implement interfaces in Go. By using interfaces, we can write flexible and reusable code that can work with different types. This is especially useful when building large and complex applications.