Go Playbook

Course › Week 2 · Methods, interfaces, errors, tests › Day 2 · lesson 9 of 42 · 20 min reading + 60–75 min practice

Interfaces

An interface lists methods, and any type that has them satisfies it, without saying so.

interfaceimplicit implementationfmt.Stringertype switchany

On this page
  1. Interfaces
  2. Two interfaces you will use every day
  3. any and type switches
  4. Coming from PHP
  5. Practice
  6. Remember

A Go interface is a list of methods. Any type that has those methods satisfies the interface, automatically. There is no implements keyword: the type does not even need to know the interface exists.

Today: declaring and using an interface, what the compiler says when a type does not fit, the two interfaces of the standard library you will use most, and any with a type switch.

Interfaces

1. A type with the right methods fits

Notifier is any type with a Notify(message string) error method. EmailNotifier and SlackNotifier both have one, so both are Notifiers.

main.go
package main

import "fmt"

type Notifier interface {
	Notify(message string) error
}

type EmailNotifier struct {
	Address string
}

func (e EmailNotifier) Notify(message string) error {
	fmt.Printf("email to %s: %s\n", e.Address, message)
	return nil
}

type SlackNotifier struct {
	Channel string
}

func (s SlackNotifier) Notify(message string) error {
	fmt.Printf("slack %s: %s\n", s.Channel, message)
	return nil
}

func notifyAll(notifiers []Notifier, message string) {
	for _, n := range notifiers {
		if err := n.Notify(message); err != nil {
			fmt.Println("notify failed:", err)
		}
	}
}

func main() {
	notifiers := []Notifier{
		EmailNotifier{Address: "ops@example.com"},
		SlackNotifier{Channel: "#ops"},
	}

	notifyAll(notifiers, "booking 1042 failed to sync")
}
$ go run .
email to ops@example.com: booking 1042 failed to sync
slack #ops: booking 1042 failed to sync

notifyAll only knows the interface. It can be given any notifier, including types written years later in another package, without changing a line.

A variable of an interface type holds two things: the concrete value (here an EmailNotifier) and its type. Calling n.Notify runs the method of whatever is inside.

2. A missing method is a compile error

The check is still strict. It just happens where the value is used as the interface, not where the type is declared:

main.godoes not compile
package main

import "fmt"

type Notifier interface {
	Notify(message string) error
}

type SMSNotifier struct {
	Number string
}

func (s SMSNotifier) Send(message string) error {
	fmt.Printf("sms to %s: %s\n", s.Number, message)
	return nil
}

func main() {
	var n Notifier = SMSNotifier{Number: "+45 1234 5678"}

	if err := n.Notify("hello"); err != nil {
		fmt.Println(err)
	}
}
go build
# hello
./main.go:19:19: cannot use SMSNotifier{…} (value of struct type SMSNotifier) as Notifier value in variable declaration: SMSNotifier does not implement Notifier (missing method Notify)

The compiler names the interface, the type and the missing method. A method with the right name but a different signature, say Notify(message string) with no error, gives a similar error, wrong type for method Notify, with the two signatures side by side.

3. The pointer receiver trap

If the method has a pointer receiver, only the pointer has the method. A plain value does not satisfy the interface:

main.godoes not compile
package main

import "fmt"

type Notifier interface {
	Notify(message string) error
}

type CountingNotifier struct {
	Sent int
}

func (c *CountingNotifier) Notify(message string) error {
	c.Sent++
	fmt.Println("sent:", message)
	return nil
}

func main() {
	counter := CountingNotifier{}
	var n Notifier = counter

	if err := n.Notify("hello"); err != nil {
		fmt.Println(err)
	}
}
go build
# hello
./main.go:21:19: cannot use counter (variable of struct type CountingNotifier) as Notifier value in variable declaration: CountingNotifier does not implement Notifier (method Notify has pointer receiver)

Notify must change Sent, so it has a pointer receiver (the methods lesson), and only *CountingNotifier has it. The fix is to store the pointer: var n Notifier = &counter. The interface then holds the address, and the count changes on the real counter.

Two interfaces you will use every day

4. fmt.Stringer: how a value prints

The fmt package defines Stringer: any type with a String() string method. Every Print function calls it. Rename the Name method of Level to String, and levels print as names:

main.go
package main

import "fmt"

type Level int

const (
	Debug Level = iota
	Info
	Warning
	Error
)

var levelNames = []string{"DEBUG", "INFO", "WARNING", "ERROR"}

func (l Level) String() string {
	if l < 0 || int(l) >= len(levelNames) {
		return fmt.Sprintf("Level(%d)", int(l))
	}
	return levelNames[l]
}

func main() {
	current := Warning

	fmt.Println(current)
	fmt.Printf("level %v, number %d\n", current, current)
	fmt.Println([]Level{Info, Error})
}
$ go run .
WARNING
level WARNING, number 2
[INFO ERROR]

%v and Println use String; %d still prints the number. It is PHP’s __toString, picked up by an interface instead of a magic name.

5. io.Writer: anything you can write to

io.Writer has one method, Write(p []byte) (n int, err error). Files, os.Stdout, network connections, HTTP responses and in-memory buffers all satisfy it. fmt.Fprintf writes to any of them.

main.go
package main

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

func writeReport(w io.Writer, counts map[string]int) error {
	for _, level := range []string{"INFO", "WARNING", "ERROR"} {
		if _, err := fmt.Fprintf(w, "%-8s %d\n", level, counts[level]); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	counts := map[string]int{"INFO": 4, "WARNING": 1, "ERROR": 2}

	if err := writeReport(os.Stdout, counts); err != nil {
		fmt.Fprintln(os.Stderr, "writing the report:", err)
		os.Exit(1)
	}

	var buffer strings.Builder
	if err := writeReport(&buffer, counts); err != nil {
		fmt.Fprintln(os.Stderr, "writing the report:", err)
		os.Exit(1)
	}
	fmt.Printf("the buffer holds %d bytes\n", buffer.Len())
}
$ go run .
INFO     4
WARNING  1
ERROR    2
the buffer holds 33 bytes

The same function writes to the terminal and to a strings.Builder, a buffer that collects text in memory. That is how you test code that prints: give it a buffer, then compare the buffer with what you expected. logstat’s report works this way from the build day on.

Fprintf returns the number of bytes written and an error. Writing to a terminal rarely fails, but writing to a file on a full disk or a closed network connection does, so the error is checked; the count is not needed and goes to _. strings.Builder’s Write has a pointer receiver, so the function gets &buffer (section 3).

any and type switches

6. any holds a value of any type

any is the interface with no methods, so every type satisfies it. A type switch finds out what is inside.

main.go
package main

import "fmt"

func describe(value any) string {
	switch v := value.(type) {
	case nil:
		return "nothing"
	case string:
		return fmt.Sprintf("text of %d bytes", len(v))
	case int:
		return fmt.Sprintf("the number %d", v)
	case []any:
		return fmt.Sprintf("a list of %d values", len(v))
	default:
		return fmt.Sprintf("something else: %T", v)
	}
}

func main() {
	fmt.Println(describe("Astrid"))
	fmt.Println(describe(42))
	fmt.Println(describe([]any{1, "two"}))
	fmt.Println(describe(4.5))
	fmt.Println(describe(nil))
}
$ go run .
text of 6 bytes
the number 42
a list of 2 values
something else: float64
nothing

In each case, v has that case’s type: a string in the string case, so len(v) works. It is PHP’s match (true) { is_string($v) => … }, checked by the compiler.

any gives up the compiler’s help, so use it only where the type really cannot be known in advance: decoded JSON of unknown shape (Week 3) is the common case. Anywhere else, a concrete type or a small interface says more.

7. A type assertion takes one type out

value.(string) claims the value is a string. With the comma-ok form, a wrong claim gives false instead of a panic.

main.go
package main

import "fmt"

func main() {
	var payload any = "booking.confirmed"

	if event, ok := payload.(string); ok {
		fmt.Println("event:", event)
	}

	if count, ok := payload.(int); !ok {
		fmt.Println("not an int; count is the zero value:", count)
	}
}
$ go run .
event: booking.confirmed
not an int; count is the zero value: 0

The same comma-ok form as a map lookup (the slices and maps lesson). Without ok, payload.(int) panics when the value is not an int; always use the two-value form on data from outside.

Coming from PHP

Notifier.php
<?php
interface Notifier
{
    public function notify(string $message): void;
}

final class EmailNotifier implements Notifier   // must name the interface
{
    public function __construct(private string $address) {}

    public function notify(string $message): void { /* … */ }
}

In PHP a class satisfies an interface only if it says implements, so the interface must exist first and the class must know it. In Go the consumer defines the interface it needs, often in its own package, and existing types fit it without being touched.

That is why Go interfaces are usually small: one or two methods, like io.Writer and fmt.Stringer. Laravel’s contracts are large by comparison; a Go program would split Illuminate\Contracts\Cache\Repository into the three methods each caller actually uses.

PracticeA Tour of Go: interfaces to Stringers, one small program

In A Tour of Go, do the methods pages from Interfaces to Exercise: Stringers. The pages on nil values inside interfaces (11 to 13) explain a trap that comes back in the error lesson.

Exercise: a price rule

Define type PriceRule interface { Apply(cents int) int; String() string }. Write two rules: PercentOff{Percent int} and FixedFee{Cents int}. Apply a slice of rules, in order, to a total of 38850 cents, and print each rule with %v and the running total after it.

Show the solution
main.go
package main

import "fmt"

type PriceRule interface {
	Apply(cents int) int
	String() string
}

type PercentOff struct {
	Percent int
}

func (p PercentOff) Apply(cents int) int {
	return cents * (100 - p.Percent) / 100
}

func (p PercentOff) String() string {
	return fmt.Sprintf("%d%% off", p.Percent)
}

type FixedFee struct {
	Cents int
}

func (f FixedFee) Apply(cents int) int {
	return cents + f.Cents
}

func (f FixedFee) String() string {
	return fmt.Sprintf("fee of %d cents", f.Cents)
}

func main() {
	rules := []PriceRule{PercentOff{Percent: 10}, FixedFee{Cents: 4500}}

	total := 38850
	for _, rule := range rules {
		total = rule.Apply(total)
		fmt.Printf("%-20v %d\n", rule, total)
	}
}
$ go run .
10% off              34965
fee of 4500 cents    39465

%% prints a literal percent sign in a Printf template. Because PriceRule includes String(), %v prints each rule by its own description.

Remember

  • Define small interfaces where they are used; types satisfy them without saying so.
  • A method with a pointer receiver belongs to the pointer: store &value in the interface.
  • Write to an io.Writer instead of os.Stdout, and tests can read what you wrote.

Tomorrow: wrapping errors with context, and finding a known error inside a chain.