Today, did you know — a struct doesn’t have to implement an interface in Go. Go uses “duck typing” (EDIT: technically they call it ‘structural typing’ because it happens at compile time, where duck typing tends to happen at run time.) 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.
This isn’t just a code style decision by the creators of Go, it has some pretty interesting implications. For a real world example how how this is useful, check out the Mock things using Go code section on 5 simple tips and tricks for writing unit tests in Go.
- Learn more about Duck Typing https://en.wikipedia.org/wiki/Duck_typing