Introduction to Interfaces

Interfaces in Go allow you to focus on what a type does rather than how it’s built. They are a way to define a set of behaviors (methods) that different types can share.

Definition

An interface is a collection of method signatures.

type shape interface {
    area() float64
    perimeter() float64
}

Implementation

A type “implements” an interface if it has methods that match the interface’s signatures. Once a type implements an interface, it can be treated as that interface type.

func printShapeData(s shape) {
    fmt.Printf("Area: %v, Perimeter: %v\n", s.area(), s.perimeter())
}

The Empty Interface

The empty interface interface{} (or any in Go 1.18+) has no requirements. Because it requires zero methods, every type in Go automatically implements it.