Go · Stage 9 – Organizing Bigger Programs · Lesson 55 of 64

A Simple Interface Example

Pass different concrete values through one small interface.

Go code

type Speaker interface { Speak() string }
type Dog struct{}
func (Dog) Speak() string { return "Woof" }
func announce(s Speaker) { fmt.Println(s.Speak()) }

announce(Dog{})
Line-by-line explanation
  1. Speaker requires Speak.
  2. Dog is a concrete type.
  3. Dog has the required method automatically.
  4. Announce accepts any Speaker.
  5. A Dog value is passed.
Expected output
Woof

This is the expected result.