liveBook · Manning

Duck typing

As explained in Go in Practice, Second Edition

Duck typing is a typing approach that determines an object's suitability by the methods and behaviors it provides rather than by explicit nominal declarations.

Duck typing determines whether a value fits an interface by the methods it provides, not by an explicit inheritance declaration. In Go, interface satisfaction is implicit: a type becomes usable wherever its method signature matches. section 3.2

Animal interface

Define an Animal interface with speak(). Cat and Dog satisfy it by implementing speak(), so an Animal variable can hold either value and invoke the method. Assigning a Llama fails at compile time until Llama also defines speak(). section 3.2

Listing 3.6 The same idea in Go
package main

import (
    "fmt"
)

type Animal interface {     #1
    speak() 
}

type Cat struct {}           #2
func (c Cat) speak() { 
    fmt.Println("meow")                      #3
}

func NewCat() *Cat {                         #4
    return &Cat{}
}

type Dog struct {}          
func (d Dog) speak() {
    fmt.Println("woof")                     
}


func NewDog() *Dog {                       
    return &Dog{}
}

type Llama struct {}        

func NewLlama() *Llama {    #5
    return &Llama{}
}

func main () {

    var a Animal

    c := NewCat()
    a = c
    a.speak()

    d := NewDog()
    a = d
    a.speak()

    l := NewLlama()
    a = l
}

Compare inheritance-style behavior with Go’s independent types, interface assignment, constructors, and method-based satisfaction. section 3.2

The approach encourages intuitive interfaces: ask what behavior a type provides rather than forcing it into an inheritance hierarchy. It also approximates some superclass fallback mechanisms while keeping the connections between types explicit through method signatures. section 3.2

How Go in Practice, Second Edition covers it

How deep it goes
Explains interface assignment and compile-time method validation, but does not descend into runtime dispatch internals.
Examples
Uses Animal, Cat, Dog, and Llama types to demonstrate successful interface assignments, compile errors, and method-based repair.
What you can do after
Apply via Go interfaces by designing method signatures and checking type satisfaction through compiler-validated assignments.
How it connects
Connects duck typing with Go interfaces, structs, inheritance, abstract classes, and object-oriented design.

Also explained in

Compare how 3 books explain duck typing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.