×

go · level 2 · unit 3 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is a job advert: any type with the skills fits.

An interface lists methods, like a job advert listing skills: type Speaker interface { Speak() string }. Any type with a Speak() string method can do the job, and Go checks that for you. There are no forms to sign.

A type that has every method an interface lists is said to it. A Dog with a Speak method satisfies Speaker, and so does a Robot, even though they are completely different structs.

Now one function can work with them all: func introduce(s Speaker). A slice can hold them all too: []Speaker{Dog{}, Robot{}}. Each value still runs its own Speak method.

package main
import "fmt"
type Speaker interface {
	Speak() string
}
type Dog struct{}
type Robot struct{}
func (d Dog) Speak() string {
	return "Woof!"
}
func (r Robot) Speak() string {
	return "Beep boop."
}
func main() {
	speakers := []Speaker{Dog{}, Robot{}}
	for _, s := range speakers {
		fmt.Println(s.Speak())
	}
}

type Dog struct{} is a struct with no fields, which is fine for a type that only needs methods.