Duck typing in Go

// Speaker types can say things.
type Speaker interface {
Say(string)
}
type Person struct {
name string
}
func (p *Person) Say(message string) {
log.Println(p.name+":", message)
}
func SpeakAlphabet(via Speaker) {
via.Say("abcdefghijklmnopqrstuvwxyz")
}
mat := new(Person)
mat.name = "Mat"
SpeakAlphabet(mat)
type SpeakWriter struct {
w io.Writer
}
func (s *SpeakWriter) Say(message string)
io.WriteString(s.w, message)
}

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mat Ryer

Mat Ryer

Founder at MachineBox.io — Gopher, developer, speaker, author — BitBar app https://getbitbar.com — Author of Go Programming Blueprints

More from Medium

[Solution] Exercise: Stringers | A Tour of Go

Use pprof to view go program stack traces

Plugging logrus into go-retryablehttp

Getting started with GO Programming Language — Part Two