TExcelTAD
Home › Go › Go Interfaces

Go Interfaces

An interface describes behaviour: it is a list of method signatures. Any type that has all of those methods automatically satisfies the interface — there is no implements keyword. This "implicit" satisfaction is one of Go's most powerful ideas: you can write code that works with anything that can do X, and new types can join in later without touching the interface.

Defining and satisfying an interface

go · try it yourself
package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
	Perimeter() float64
}

type Rect struct{ W, H float64 }
type Circle struct{ R float64 }

func (r Rect) Area() float64      { return r.W * r.H }
func (r Rect) Perimeter() float64 { return 2 * (r.W + r.H) }

func (c Circle) Area() float64      { return math.Pi * c.R * c.R }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.R }

func describe(s Shape) {
	fmt.Printf("%T: area %.2f, perimeter %.2f\n", s, s.Area(), s.Perimeter())
}

func main() {
	shapes := []Shape{Rect{3, 4}, Circle{1}, Rect{2, 2}}
	for _, s := range shapes {
		describe(s)
	}
}
main.Rect: area 12.00, perimeter 14.00
main.Circle: area 3.14, perimeter 6.28
main.Rect: area 4.00, perimeter 8.00

Neither Rect nor Circle mentions Shape. They satisfy it simply because they have Area() and Perimeter() with the right signatures.

Missing methods are caught at compile time

If a type lacks a method, using it as the interface fails to compile with a clear message:

go · try it yourself
package main

type Speaker interface {
	Speak() string
}

type Rock struct{}

func main() {
	var s Speaker = Rock{}
	_ = s
}
# command-line-arguments
./example.go:10:18: cannot use Rock{} (value of struct type Rock) as Speaker value in variable declaration: Rock does not implement Speaker (missing method Speak)

Small interfaces from the standard library

Go favours tiny interfaces, often with a single method. A few you will meet everywhere:

Interface Method Implemented by
fmt.Stringer String() string anything that wants a custom print format
error Error() string every error value
io.Reader Read(p []byte) (n int, err error) files, network connections, strings.Reader…
io.Writer Write(p []byte) (n int, err error) files, os.Stdout, bytes.Buffer, HTTP responses…
sort.Interface Len, Less, Swap collections sortable with sort.Sort

Because fmt.Fprintf accepts any io.Writer, the same code can write to the terminal, a file or a buffer in memory:

go · try it yourself
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func writeReport(w io.Writer, name string, score int) {
	fmt.Fprintf(w, "%s scored %d\n", name, score)
}

func main() {
	writeReport(os.Stdout, "Ana", 91) // to the terminal

	var sb strings.Builder // also an io.Writer
	writeReport(&sb, "Ben", 78)
	writeReport(&sb, "Cy", 85)
	fmt.Print("buffered:\n", sb.String())
}
Ana scored 91
buffered:
Ben scored 78
Cy scored 85

Pointer receivers and interfaces

If a method has a pointer receiver, only the pointer type has that method. So *T satisfies the interface, but T does not.

go · try it yourself
package main

import "fmt"

type Resetter interface {
	Reset()
}

type Timer struct{ Seconds int }

func (t *Timer) Reset() { t.Seconds = 0 }

func main() {
	t := Timer{Seconds: 42}
	var r Resetter = &t // ok: *Timer has Reset
	r.Reset()
	fmt.Println(t.Seconds)
	// var bad Resetter = t   // compile error: Timer does not implement Resetter
}
0

The empty interface: any

The interface with no methods, interface{}, is satisfied by every type. Go 1.18 added the alias any for it. Use it when you truly accept anything — like fmt.Println(a ...any) — but prefer specific types or generics otherwise, because you lose compile-time checking.

go · try it yourself
package main

import "fmt"

func main() {
	var box any
	box = 42
	fmt.Printf("%v (%T)\n", box, box)
	box = "now a string"
	fmt.Printf("%v (%T)\n", box, box)

	mixed := []any{1, "two", 3.0, true, nil}
	fmt.Println(len(mixed), mixed)
}
42 (int)
now a string (string)
5 [1 two 3 true <nil>]

Interface values and nil

An interface value holds two things: a concrete type and a value of that type. It is nil only when both are unset. A practical rule: return a literal nil for "no error", never a nil pointer of a concrete error type.

Tip: "Accept interfaces, return structs." Let functions take the smallest interface they need (e.g. io.Reader), and return concrete types. Define interfaces where they are used, not where types are implemented.

Test yourself

How does a type declare that it implements an interface?

  1. With the implements keyword
  2. It doesn't — having the methods is enough
  3. By embedding the interface
  4. With a type annotation

Save() is defined on *Doc. Which satisfies interface{ Save() }?

  1. Doc only
  2. *Doc only
  3. Both Doc and *Doc
  4. Neither

What is any?

  1. A generic type parameter
  2. An alias for interface{}
  3. A keyword for dynamic typing
  4. A package