go · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two languages, one function. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
type Greeter interface {
Greet() string
}
type English struct{}
type French struct{}
func (e English) Greet() string {
return "Hello"
}
func (f French) Greet() string {
return "Bonjour"
}
func welcome(g Greeter, name string) {
fmt.Println(g.Greet() + ", " + name + "!")
}
func main() {
welcome(French{}, "Sam")
welcome(English{}, "Zoe")
}
your turn
Your turn. Teach the cow to speak.
Give Cow the method that Speaker asks for, so it can join the slice. Then choose what the cow says and run it.
output
press run to see what happens
fix it
The duck does not count as a Speaker. Fix it!
output
press run to see what happens
- Read the error. Which method does Go say
Duckis missing? Duckdoes have a method, but its name starts with a small s. Go is case-sensitive.- Change speak to Speak on line 7, then run.
nailed it
one function, many types. :D
- An interface lists the methods a type must have.
- Any type with those methods satisfies it, with no sign-up.
- Functions and slices can use an interface to hold many types.
new words in your collection
- interface
- satisfy
This lesson isn’t saved. A free account remembers every lesson you finish.