Skip to content

Describe Behavior with an Interface

The Course
•
25 min study

The queue's report prints tasks today. Tomorrow it might print notes or reminders too, and you don't want a separate showTask, showNote and showReminder that differ only in the type of their parameter. What the report needs from each item is one thing: a label. An interface lets a function say exactly that, "give me anything that has a Label() string method", and nothing more.

An interface type lists method signatures. A type implements it by having those methods, with no separate declaration: Go checks the methods when you use the value. Keep interfaces narrow, so a caller depends only on the behaviour it actually uses.

Predict and run

Which method does show call for each argument?

Predict, then run Go
package main

import (
	"fmt"
)

type Labeled interface{ Label() string }

type Task struct{ Title string }
type Note struct{ Text string }

func (t Task) Label() string { return "Task: " + t.Title }
func (n Note) Label() string { return "Note: " + n.Text }
func show(item Labeled)      { fmt.Println(item.Label()) }

func main() {
	show(Task{Title: "Read"})
	show(Note{Text: "Check references"})
}
Check your prediction
Text
Task: Read
Note: Check references

What an interface value holds

An interface value is a pair: the concrete value you stored, and its type. Trace the first call. show(Task{Title: "Read"}) stores a Task in item, together with the fact that it is a Task. item.Label() looks up Label for the stored type and calls Task's method on the stored value. The second call stores a Note, so the same line in show calls Note's method. show never learns which concrete types exist.

When a type doesn't fit

Go checks the method set where the value is used, and the message says what is missing. Passing a number fails because int has no methods at all:

Text
cannot use 42 (constant of type int) as Labeled value in argument to show: int does not implement Labeled (missing method Label)

A method with the right name but a different signature doesn't count either. If Reminder's method were Label() []byte:

Text
cannot use Reminder{…} (value of struct type Reminder) as Labeled value in argument to show: Reminder does not implement Labeled (wrong type for method Label)
		have Label() []byte
		want Label() string

The have and want lines are worth reading first: they put the two signatures side by side.

Practice

Exercise

Your turn

A study plan mixes readings and videos. A reading takes 2 minutes per page, and a video takes its length plus 5 minutes for notes. Define an interface with one method that reports an item's minutes, give Reading and Video that method, and write plan, which takes a slice of the interface and returns the total. The starter's plan has a 30-page reading and a 12-minute video, so it prints this once your code works:

Text
Plan: 77 min
Your working space Go
package main

import (
	"fmt"
)

type Reading struct{ Pages int }
type Video struct{ Length int }

func main() {
	r := Reading{Pages: 30}
	v := Video{Length: 12}
	fmt.Println(r, v)
}
Hint 1: the idea

plan only needs to ask each item one question, so the interface has one method, for example Minutes() int. Each type answers with its own rule.

Hint 2: a first step

Declare type Estimator interface{ Minutes() int } and give Reading its method. Write plan(items []Estimator) int and call it with []Estimator{r}: you should see 60. Then add Video.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Estimator interface{ Minutes() int }

type Reading struct{ Pages int }
type Video struct{ Length int }

func (r Reading) Minutes() int { return r.Pages * 2 }
func (v Video) Minutes() int   { return v.Length + 5 }

func plan(items []Estimator) int {
	total := 0
	for _, item := range items {
		total += item.Minutes()
	}
	return total
}

func main() {
	r := Reading{Pages: 30}
	v := Video{Length: 12}
	fmt.Printf("Plan: %d min\n", plan([]Estimator{r, v}))
}
Text
Plan: 77 min

A third kind of item, such as a quiz, needs only its own Minutes method: plan doesn't change. The interface is named after what plan needs, not after the types that happen to provide it, which is the usual Go style.

Was this article helpful?

Your response is saved on this device.