Duck Typing in Go

Hello everyone!

As I mentioned in a previous post, I’m currently learning Go to use in some of my work projects. In this short post, I’ll explain how to use duck typing in Go, which was quite challenging for me when I first started learning the language.

To begin, let’s look at a simple example in Python:

class Duck:
    def quack(self):
        print("Quack, quack!")


class Person(Duck):
    pass


def quack(obj):
    obj.quack()

def main():
    donald = Duck()
    john = Person()

    quack(donald) -- Quack, quack!
    quack(john) -- Quack, quack!

In this somewhat quirky example, the Person class can “quack” like a Duck because it inherits from the Duck class. In Python, we don’t need to explicitly declare the type of the object in the function; we simply call the method we want to use.

Now, let’s see how to achieve something similar in Go:

package main

import "fmt"

type Dog interface {
	Bark()
}

type Cat interface {
	Meow()
}

type Shihtzu struct {
	Name string
}

type Chartreux struct {
	Name string
}

func (s Shihtzu) Bark() {
	message := fmt.Sprintf("Type: %T - My name is %s! Bark! Bark! Bark!", s, s.Name)
	fmt.Println(message)
}

func (c Chartreux) Meow() {
	message := fmt.Sprintf("Type: %T - My name is %s! Meow! Meow! Meow! ", c, c.Name)
	fmt.Println(message)
}

func main() {
	var dog Dog
	dog = Shihtzu{Name: "Puppy"}
	dog.Bark()

	var cat Cat
	cat = Chartreux{Name: "Kitty"}
	cat.Meow()
}

The example code above is in this repository on github.

In this Go example, we have two interfaces, Dog and Cat, and two structs, Shihtzu and Chartreux. The Dog interface defines a method Bark, while the Cat interface defines a method Meow. The structs Shihtzu and Chartreux implement the Bark and Meow methods, respectively. It’s important to note that although it’s not explicitly stated in the code, these structs are implementing the interfaces.

In Go, we implement an interface by simply defining the required methods, without needing to declare that the struct is explicitly implementing the interface.

In other words, we don’t need to state that Shihtzu is a Dog—we just need to implement the Bark method for the Shihtzu struct, and Go automatically understands that Shihtzu satisfies the Dog interface.

This is quite different from languages like Python or Java, but once you get the hang of it, it’s straightforward and easy to use.

I hope this post helps you better understand Go and how duck typing works in the language!