Interfaces

Intermediate

Introduction

Imagine a program that draws shapes. It should be able to ask any shape for its area, whether the shape is a circle, a rectangle or something you invent next year. In Go, this is done with an interface. An interface describes what a value can do, not what it is. Code that is written against an interface works with every type that can do the job. This makes programs flexible, easy to test and easy to extend, and interfaces are the most important idea for designing Go programs.

How it works

An interface is a type that lists method signatures:

type Shape interface {
	Area() float64
}

In Go a type satisfies an interface implicitly: if it has all the methods, it is a Shape. There is no implements keyword. So if Rect and Circle each have an Area() float64 method, both can be used as a Shape:

shapes := []Shape{Rect{2, 3}, Circle{1}}
for _, s := range shapes {
	fmt.Println(s.Area())
}

The slice holds different types, and the loop does not care which one it is. A function can take a Shape parameter in the same way and work with all of them. This is called polymorphism: one piece of code, many types.

An interface value holds a concrete value inside it. To find out which type it is, use a type switch:

switch v := s.(type) {
case Rect:
	fmt.Println("rect", v.W)
case Circle:
	fmt.Println("circle", v.R)
}

Or use a type assertion with comma ok: r, ok := s.(Rect); ok is false when the value is not a Rect. Without the ok form, a wrong assertion stops the program.

The empty interface, interface{}, lists no methods, so every value satisfies it. It can hold anything, but you must use an assertion to use the value, so use it rarely.

Two standard interfaces are worth knowing. fmt.Stringer has one method, String() string, and fmt uses it to print a value. sort.Interface has three methods, Len, Less(i, j int) bool and Swap(i, j int); if your type has them, sort.Sort can sort it. And error, which you will meet in the next lesson, is also just an interface with an Error() string method.

A good rule for Go is to keep interfaces small, often only one or two methods, and to define them where they are used.

Example

package main

import (
	"fmt"
	"math"
)

type Shape interface {
	Area() float64
}

type Rect struct {
	W, H float64
}

type Circle struct {
	R float64
}

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

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

func (c Circle) String() string {
	return fmt.Sprintf("Circle(r=%.1f)", c.R)
}

func Describe(s Shape) {
	fmt.Printf("area %.2f\n", s.Area())
}

func main() {
	shapes := []Shape{Rect{2, 3}, Circle{1}}
	for _, s := range shapes {
		Describe(s)
	}
	for _, s := range shapes {
		switch v := s.(type) {
		case Rect:
			fmt.Println("rect with width", v.W)
		case Circle:
			fmt.Println("circle with radius", v.R)
		}
	}
	_, isRect := shapes[0].(Rect)
	_, isCircle := shapes[0].(Circle)
	fmt.Println(isRect, isCircle)
	fmt.Println(shapes[1])
}

Line by line

  1. Shape lists one method, Area() float64. Rect and Circle each have it, so both are shapes without any extra declaration.
  2. Describe takes a Shape and works with any of them.
  3. The slice shapes holds a Rect and a Circle together, and the loop calls Area on each.
  4. The type switch checks the real type of each shape and uses its fields.
  5. s.(Rect) with comma ok tells whether the first shape is a Rect.
  6. Circle also has a String method, so Println prints it in the form the method gives.

Expected result

area 6.00
area 3.14
rect with width 2
circle with radius 1
true false
Circle(r=1.0)

In the real world

Interfaces are everywhere in real Go code. io.Reader and io.Writer let the same code read from a file, a network connection or a string. A web handler is an interface, so a server can work with any handler. Because a type only needs the right methods, you can replace a real database with a fake one in a test without changing the program. The Go proverb says: accept interfaces, return structs.

Common mistakes

  • Making big interfaces with many methods. Small ones are easier to satisfy.
  • Forgetting a pointer receiver issue: if a method has a pointer receiver, only the pointer type satisfies the interface.
  • Using a type assertion without ok on a value that may have another type.
  • Using interface everywhere and losing the help of the type checker.
  • Declaring an interface before you need one. Start with real types.

Best practices

  • Keep interfaces small and name them after what they do, such as Reader or Shape.
  • Define the interface in the code that uses it.
  • Use a type switch to handle a few known cases.

Summary

An interface lists methods, and any type that has them satisfies it without any declaration. Code that takes an interface works with all such types. A type switch or an assertion with comma ok finds the concrete type, interface accepts anything, and standard interfaces such as Stringer and sort.Interface let your types work with fmt and sort.

Quick check

1. How does a Go type say that it implements an interface?
2. What can a variable of type Shape hold?
3. What does r, ok := s.(Rect) do when s holds a Circle?
4. Which methods does sort.Interface need?
5. What is interface{} good for?

Key takeaways

  • An interface lists methods; a type satisfies it automatically by having them.
  • Code written against an interface works with every type that has those methods.
  • A type switch or v.(T) with comma ok finds the real type inside an interface value.

Practice problems for this lesson

Was this lesson clear?

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.