Interfaces in Go

Small interfaces win

An interface in Go is a short list of method signatures. Any type that provides those methods satisfies the interface, so tiny one-method interfaces stay easy to reuse across files, buffers, and network code.

package main import "fmt" type Speaker interface { Speak() string } type Dog struct{} func (Dog) Speak() string { return "woof" } func Announce(s Speaker) { fmt.Println(s.Speak()) } func main() { Announce(Dog{}) }

Announce accepts any Speaker without knowing the concrete type behind it. Add a Cat or a Robot with a Speak method, and the same function welcomes them with no changes.

Implicit implementation

Go has no implements keyword. The moment a type defines every method of an interface, it satisfies that interface, and the compiler checks the match where the value is used.

package main import "fmt" type Shape interface { Area() float64 } type Rect struct { W float64 H float64 } func (r Rect) Area() float64 { return r.W * r.H } func AreaOf(s Shape) float64 { return s.Area() } func main() { fmt.Println(AreaOf(Rect{W: 3, H: 4})) }

Rect never mentions Shape, yet AreaOf accepts it. This keeps packages decoupled: the type and the interface can live in different packages that never import each other.

The empty interface any

The predeclared type any is an interface with no methods, so every value satisfies it. It fits holes that truly accept anything, such as printing or decoding mixed data, while behavior you can name deserves a small interface or a type parameter instead.

package main import "fmt" func PrintAll(vals ...any) { for _, v := range vals { fmt.Println(v) } } func main() { PrintAll(1, "hi", true) }

The PrintAll function takes any number of values of any type and prints each one. Reach for any at the edges of a program, and push it inward only when a precise type would complicate the design.

Type switches on any

To look inside an any value, use a type switch: a switch with a short declaration and one case per type. Each branch receives the value at its own static type, and the default branch catches everything unexpected.

package main import "fmt" func Describe(x any) { switch v := x.(type) { case int: fmt.Println("int:", v) case string: fmt.Println("string:", v) default: fmt.Println("other") } } func main() { Describe(7) Describe("hi") Describe(1.5) }

Describe prints ints and strings differently and admits everything else as other. Prefer a type switch over long chains of single assertions when three or more types are possible.

Next: Embedding instead of inheritance

Article author: Arthur Isaev