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 11 hands-on exercises. Estimated time: 26 minutes.
- What is an interface — An interface is like a library card catalog. It lists what you need to *do* — not who you need to *be*.\n"Must be able t…
- Define and satisfy an interface — Your turn. Define a `Media` interface that requires `Pages() int`.\nThen make both `Book` and `Audiobook` satisfy it by …
- aha — a slice of interfaces treats everything the same — Because all three media types satisfy `Media`, you can store them in a `[]Media` and treat them uniformly.\nAdd an `Audi…
- The Stringer interface — Remember `String()` from the Methods chapter? That was an interface all along.\n`fmt.Stringer` requires one method: `Str…
- Type assertion — Sometimes you have an interface value and you need the concrete type underneath.\n`concrete, ok := interfaceVal.(Concret…
- 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 (any) — `interface{}` (or `any` in newer Go) has zero methods — which means *every* type satisfies it.\nUseful for generic conta…
- Composing interfaces — Interfaces can embed other interfaces. The composed interface requires all methods from all embedded interfaces.\n`type …
- Implicit satisfaction — no implements keyword — This is the most important thing about Go interfaces. In Java, you write `implements Speaker`. In Go, you just... have t…
- Fix the broken interface — Bug hunt time! The code tries to use `DVD` as a `Media`, but it won't compile.\nRead the error, figure out what's missin…
- Build a library checkout system — No starter code. Build a library checkout system from scratch:\n1. Define a `LibraryItem` interface: `Checkout(cardNumbe…
Go Interfaces concepts covered
- What something can do, not what it is