Introduction

Interfaces are a powerful concept in Go that enables you to achieve polymorphism, allowing different types to be used interchangeably. In this guide, we'll explore what interfaces are, how to define them, and provide sample code to demonstrate their usage for achieving polymorphism.


What Are Interfaces?

In Go, an interface is a type that specifies a set of method signatures. Any type that implements all the methods defined by an interface is considered to implement that interface. This allows for a high degree of abstraction and polymorphism.


Defining Interfaces

To define an interface in Go, you list the method signatures without implementing them. Here's an example:

package main
import "fmt"
// Define an interface "Shape" with a "Area" method.
type Shape interface {
Area() float64
}
// Define a struct type "Rectangle" with width and height fields.
type Rectangle struct {
Width float64
Height float64
}
// Implement the "Area" method for "Rectangle".
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
// Define a struct type "Circle" with a radius field.
type Circle struct {
Radius float64
}
// Implement the "Area" method for "Circle".
func (c Circle) Area() float64 {
return 3.14 * c.Radius * c.Radius
}
func printArea(s Shape) {
fmt.Printf("Area: %f\n", s.Area())
}
func main() {
rect := Rectangle{Width: 5, Height: 3}
circle := Circle{Radius: 2}
printArea(rect) // Polymorphic call with Rectangle
printArea(circle) // Polymorphic call with Circle
}

In this code, we define an interface "Shape" with an "Area" method, and then implement the "Area" method for both "Rectangle" and "Circle" types. The "printArea" function demonstrates polymorphic behavior by accepting any type that implements the "Shape" interface.


Empty Interfaces

In Go, an empty interface can hold values of any type. It's a powerful tool for handling arbitrary data. Here's an example:

package main
import "fmt"
func describe(i interface{}) {
fmt.Printf("Type: %T, Value: %v\n", i, i)
}
func main() {
describe(42)
describe("Hello, Go!")
describe([]string{"apple", "banana", "cherry"})
}

In this code, we define a function "describe" that accepts an empty interface as a parameter. It can describe and handle values of different types.


Further Resources

To continue learning about interfaces in Go and polymorphism, consider these resources: