Thomas Nguyen
Thomas Nguyen's Blog

Thomas Nguyen's Blog

Duck typing in Go

Duck typing in Go

Thomas Nguyen's photo
Thomas Nguyen
·Jun 15, 2022·

1 min read

Today, did you know — a struct doesn’t have to implement an interface in Go. Go uses “duck typing”.

What is the duck typing?

If it looks like a duck, and it quacks like a duck, then it is a duck.

If it has a set of methods that match an interface, then you can use it wherever that interface is needed without explicitly defining that your types implement that interface.

Check out this interface:

// Speaker types can say things.
type Speaker interface {
  Say(string)
}

Anything with a matching Say method can be called a Speaker.

We don’t do anything special to our struct types to satisfy this interface:

type Person struct {
  name string
}

func (p *Person) Say(message string) {
  log.Println(p.name+":", message)
}

Now assume we have a method that takes a Speaker:

func SpeakAlphabet(via Speaker) {
  via.Say("abcdefghijklmnopqrstuvwxyz")
}

We can use our type look:

mat := new(Person)
mat.name = "Mat"
SpeakAlphabet(mat)

And imagine if another package exists that provides this type:

type SpeakWriter struct {
  w io.Writer
}

func (s *SpeakWriter) Say(message string)
  io.WriteString(s.w, message)
}

We could use that too — without the other package even knowing about our interface.

Reference: https://medium.com/@matryer/golang-advent-calendar-day-one-duck-typing-a513aaed544d

 
Share this