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 defines a set of method signatures. Any type that has those methods satisfies the interface automatically —…
- Define and satisfy an interface — Define a `Shape` interface with one method: `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 — You already used this in the Methods chapter without knowing what it was.
- 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 — An interface with no methods — `interface{}` — is satisfied by every type in Go. It is the "accept anything" type.
- 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 — The code below tries to use `Speaker` interface with `Robot`. But it does not compile — `Robot` is missing something.
- Build a notification system — No starter code.
Go Interfaces concepts covered
- What something can do, not what it is