Go Tutorial: Interfaces
Write code that works with anything. Interfaces let you define behaviour without caring about the concrete type.
What something can do, not what it is
In Go, an interface defines a set of methods. Any type that has those methods automatically satisfies the interface — no `implements` keyword, no declaration required.
This is Go's most powerful feature. It lets you write functions that accept any type that can do a certain thing. A `Shape` that can calculate its `Area()`. A `Writer` that can `Write()` bytes. A `Stringer` that knows how to turn itself into a string.
Your code stays flexible. Your types stay decoupled. Everything just works.
Thirteen steps.
What you'll learn in this Go interfaces tutorial
This interactive Go tutorial has 13 hands-on exercises. Estimated time: 26 minutes.
- What is an interface — An interface is like a job posting. It lists what you need to *do* — not who you need to *be*.
- Define and satisfy an interface — Your turn. Define a `Shape` interface that requires `Area() float64`.
- Interfaces with multiple methods — An interface can require any number of methods. A type must implement all of them to satisfy the interface.
- A slice of interfaces — Because all three shapes satisfy `Shape`, you can store them in a `[]Shape` and treat them uniformly.
- The Stringer interface — Remember `String()` from the Methods chapter? Surprise — that was an interface all along.
- Interface as function parameter — Interfaces shine when used as function parameters. The function does not care about the concrete type — only that it has…
- Type assertion — Sometimes you have an interface value and you need to access the concrete type underneath.
- Type switch — When you need to handle multiple concrete types from an interface, a type switch is cleaner than chaining type assertion…
- The empty interface — `interface{}` (or `any` in newer Go) has zero methods — which means *every* type satisfies it.
- Composing interfaces — Interfaces can embed other interfaces. The composed interface requires all methods from all embedded interfaces.
- Implicit satisfaction — no implements keyword — This is the most important thing about Go interfaces.
- Fix the broken interface — Bug hunt time! The code tries to use `Robot` as a `Speaker`, but it won't compile.
- Build a notification system — Build a notification system from scratch.
Go Interfaces concepts covered
- What something can do, not what it is