BuildBot

Go by Contrast

Interfaces (implicit)

Lesson 3 of 5

What you'll learn

  • Understand Go's implicitly-satisfied interfaces
  • Contrast with TS structural typing and the implements keyword
  • See how interface dispatch picks the right method at runtime

A Go interface is a set of method signatures. A type satisfies the interface simply by having those methods — there is no implements clause, and the type doesn't even need to know the interface exists. This is structural typing, like TypeScript, but Go applies it to behavior (methods) rather than just data shape.

type Speaker interface {
    Speak() string
}

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

type Cat struct{}
func (c Cat) Speak() string { return "Meow" }

// Dog and Cat satisfy Speaker automatically — no declaration needed.
func announce(s Speaker) string {
    return "It says: " + s.Speak()
}

In TypeScript, structural typing gives you something similar — but classes that want to be explicit use implements:

interface Speaker {
  speak(): string;
}

class Dog implements Speaker {
  speak() { return "Woof"; }
}

function announce(s: Speaker): string {
  return "It says: " + s.speak();
}

Implicit satisfaction decouples code

Because Go interfaces are implicit, you can define an interface in your package that some third-party type already satisfies — without touching that type. This is why Go's standard library is full of tiny interfaces like io.Reader (one method, Read) and io.Writer (one method, Write). Any type with the right method plugs in.

When you call s.Speak() on a Speaker, Go performs dynamic dispatch at runtime: the interface value remembers the concrete type stored in it and calls that type's method.

Small interfaces win

Idiomatic Go favors one- or two-method interfaces. The proverb is "the bigger the interface, the weaker the abstraction." Accept narrow interfaces as function parameters; return concrete structs.

The challenge is a JS model of interface dispatch — different "types" that each provide a speak method, called through one common function.

Interface dispatch (JS model)

Run it. This models Go's implicit interface satisfaction: any value with a speak() method fits, and dispatch picks the right one.

Loading editor…
Knowledge check

What makes a Go type satisfy an interface?

Next: Go's headline feature — cheap concurrency with goroutines and channels.

Saved on this device. Sign in to sync your progress everywhere.