ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Go (Golang) Tutorial• 7 min read

Interfaces & Implicit Duck Typing

Zero implements keyword: If it walks like a duck, it is a duck

In Go, interfaces are satisfied IMPLICITLY. There is no implements keyword. If a type defines all the methods declared in an interface, it automatically implements that interface.

The Power of Implicit Interfaces

Decoupled Architecture: You can declare an interface in your package that matches types created by third-party libraries without modifying their code.

Standard Library: The io.Reader and io.Writer interfaces have only 1 method each, yet power networking, files, and HTTP across Go.

Implicit Interface Implementation
package main

import "fmt"

type Speaker interface {
    Speak() string
}

type Dog struct{}
func (d Dog) Speak() string { return "Woof!" }

type Robot struct{}
func (r Robot) Speak() string { return "Beep Boop!" }

func Announce(s Speaker) {
    fmt.Println("Speaker says:", s.Speak())
}

func main() {
    Announce(Dog{})   // Automatically satisfies Speaker!
    Announce(Robot{}) // Zero implements keyword!
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

How does a Go struct declare that it implements an interface?