~/Go Interfaces Explained
Sep 14, 2025
First read the official interface documentation to understand the interface construct in the Go language.
Interface Value
An interface in Go is a type that specifies zero or more method signatures. Any type that implements those methods implicitly implements the interface, without requiring explicit declaration, unlike languages like Java. Go uses structural typing, not nominal typing.
Purpose of Interfaces
The main points of interfaces are:
- Define public APIs contract.
- Enable explicit abstraction and polymorphism.
- Enable dependency injection and clean separation of concerns.
- Enable mocking and testing by substituting implementations.
Getting Real: Repository Pattern Example
Suppose you need an object for storing and fetching users. In-memory or SQL both satisfy these contracts.
You might create an in memory version:
|
|
and a SQL version:
|
|
Now you can write code that works with any UserRepository, abstracting away implementation:
Benefits
- Testing becomes easier, you can mock/passthrough memory implementation.
- Inversion of Control allows for runtime composition and substitutability.
- Open-Closed Principle, allows extending without editing code that depends on the contract.
- Decoupled architecture makes for robust maintainable codebases.
Trivia
- The idea comes from similar constructs in Java and CSharp.
- Satirical note, in Go code review comments, it is common to warn: Do not design interfaces upfront. Only define when you see multiple concrete types.
- Go interfaces are extensively used in io.Reader and http.Handler.
- Limiting interface size to a few methods is recommended idiomatically.
- In duck typing fashion, “if it walks like a duck…” describes how Go infers implementation.
- Interface{} is the most general type, representing any value.
- In Go error handling, error is itself an interface.
Adjacent Patterns and Misuses
- Anti-pattern: over-abstracting by defining interfaces when only one implementation exists (YAGNI principle).
- Composition over inheritance: Go has no classes, embeds interfaces for similar behavior.
- Consider the strategy pattern for interchangeable business logic, implementations.
See also Effective Go interfaces and A Tour of Go: Interfaces.
Related Reading
- Go Proverbs: Make the zero value useful
- Minimal interfaces
- Go by Example: Interfaces
- Go Interface Segregation Principle
- Go testing and mocking
- Design philosophy of Go interfaces
This summary should clarify the contract, polymorphism, and practical motivation of Go interfaces.