Interfaces & Composition
- Explain how an interface value is represented and predict when
err != nilis true for a "nil" error. - Design small, consumer-defined interfaces (ports) for payment providers, repositories and clocks.
- Use type assertions, type switches and optional-capability checks correctly.
- Compose behaviour with embedding and decorators instead of inheritance, and stream data with
io.Reader/io.Writer.
TL;DR
- Interfaces are satisfied implicitly: a type implements an interface by having the methods. The consumer, not the provider, should usually define the interface.
- Keep interfaces small (one to three methods).
io.Readeris the model: one method, hundreds of implementations, endless composition. - An interface value is a pair (dynamic type, value). It is
nilonly when both are nil. Returning a nil*MyErraserrorproduces a non-nil error. - Accept interfaces, return structs: functions take the narrowest behaviour they need and constructors return concrete types so callers keep full access.
- Embedding promotes fields and methods; use it to compose and decorate. It is not inheritance — no virtual dispatch to the outer type.
- Interface calls cost an indirect call and block inlining; values stored in an interface often escape to the heap. Fine at service boundaries, think twice in hot inner loops.
Why it matters
Bank and e-commerce systems are full of things that vary behind a stable contract:
- Payment providers / acquirers — card processors, wallets, domestic switches (e.g. NAPAS in Vietnam), each with its own API. Checkout should depend on "something that can authorize and capture", not on a vendor SDK.
- Storage — the transfer use case needs "load account, save posting"; whether that is PostgreSQL, a test fake or a cache-backed repo is an adapter concern.
- Time and IDs — a
ClockandIDGeneratorport make cut-off-time logic ("transfers after 15:30 settle next business day") testable. - Files and streams — settlement and reconciliation files are hundreds of MB; you want to decompress, hash, parse and upload them as streams, not load them into memory.
Getting interfaces wrong produces the two classic Go smells: giant "Java-style" interfaces declared next to their single implementation, and the nil-interface bug that turns a successful payment into a reported failure.
Core concepts
Implicit satisfaction and consumer-defined interfaces
There is no implements keyword. If *stripe.Client has Authorize(ctx, req) (AuthResult, error), it satisfies any interface with that method — including one written after the client, in a package the client has never heard of.
This flips the usual ownership: the consumer declares the interface it needs, and the interface lives next to the consumer.
package checkout
import "context"
// PaymentAuthorizer is the port checkout needs. It is defined here,
// by the consumer, and contains only what checkout actually calls.
type PaymentAuthorizer interface {
Authorize(ctx context.Context, req AuthRequest) (AuthResult, error)
}
type Service struct {
psp PaymentAuthorizer
orders OrderStore
}
func NewService(psp PaymentAuthorizer, orders OrderStore) *Service {
return &Service{psp: psp, orders: orders}
}
Adapters satisfy it without importing an "interfaces" package. A compile-time assertion documents and enforces the intent at zero runtime cost:
var _ checkout.PaymentAuthorizer = (*Client)(nil)
Dependencies point into the core: exactly the shape of Clean & Hexagonal Architecture, achieved with no framework.
Small interfaces
Rob Pike's proverb puts it as "the bigger the interface, the weaker the abstraction." A one-method interface can be implemented by a function type, by a test fake in three lines, or by a decorator. A 15-method PaymentGateway interface forces every fake to stub 14 methods it doesn't care about and couples every consumer to every method.
Practical rules:
- Define interfaces when you have (or genuinely expect) two implementations — and a test fake counts. Don't create an interface "just in case" for a type with one implementation and no tests needing substitution.
- Split by consumer:
Authorizer,Capturer,Refunderrather than one gateway interface. A refund worker depends only onRefunder. - Function types can satisfy single-method interfaces, like
http.HandlerFunc:
type AuthorizerFunc func(ctx context.Context, req AuthRequest) (AuthResult, error)
func (f AuthorizerFunc) Authorize(ctx context.Context, req AuthRequest) (AuthResult, error) {
return f(ctx, req)
}
Interface values: type plus value
At runtime a non-empty interface value is two words: a pointer to an itab (dynamic type + method table) and a pointer to (or copy of) the data. any (empty interface) stores a type pointer instead of an itab.
The famous bug:
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid " + e.Field }
// BUG: always returns a non-nil error, even for valid input.
func validate(amount int64) error {
var verr *ValidationError
if amount <= 0 {
verr = &ValidationError{Field: "amount"}
}
return verr // (type=*ValidationError, data=nil) when valid
}
// Fix: return the literal nil on the success path.
func validateFixed(amount int64) error {
if amount <= 0 {
return &ValidationError{Field: "amount"}
}
return nil
}
In a checkout handler, the buggy version makes every valid payment look like a failure — or worse, makes a caller skip a ledger write. Rules: never declare a concrete error-pointer variable to return as error; return nil literally; keep function results typed as error, not *MyErr.
Two related facts:
- Interface equality compares dynamic type and value. Comparing two interfaces whose dynamic type is not comparable (a slice, map, func) panics at runtime — same for using such a value as a
map[any]Vkey. - A method with a pointer receiver can be called on a nil pointer stored in an interface; it only crashes if it dereferences. Some types use this deliberately (a nil
*Loggerthat discards).
Type assertions and type switches
// Comma-ok form never panics.
if r, ok := w.(io.ReaderFrom); ok {
_, err := r.ReadFrom(src)
return err
}
// Single-value form panics on mismatch — use only when a mismatch is a programming bug.
captured := evt.(PaymentCaptured)
Type switches dispatch on dynamic type, e.g. for domain events consumed from a queue:
func (p *Projector) Apply(evt Event) error {
switch e := evt.(type) {
case PaymentCaptured:
return p.credit(e.MerchantID, e.Amount)
case PaymentRefunded:
return p.debit(e.MerchantID, e.Amount)
case nil:
return errors.New("nil event")
default:
return fmt.Errorf("unknown event %T", e)
}
}
To keep the set of events closed (so the default branch really is a bug), use a sealed interface — an unexported method only types in your package can implement:
type Event interface{ isEvent() }
type PaymentCaptured struct {
MerchantID string
Amount int64
}
func (PaymentCaptured) isEvent() {}
Use errors.As / errors.Is, not type assertions, for errors: assertions don't see through %w wrapping (see Error Handling).
Optional capabilities ("interface upgrades") are a powerful standard-library pattern: io.Copy checks whether the source implements io.WriterTo or the destination io.ReaderFrom and uses the faster path. The catch: wrapping a value (middleware wrapping http.ResponseWriter) hides its extra methods. Since Go 1.20, http.NewResponseController(w) finds Flush, SetWriteDeadline etc. through wrappers that implement Unwrap() http.ResponseWriter.
Embedding for composition
Three kinds of embedding, each with a different purpose:
- Interface in interface — union of method sets:
type ReadWriter interface { Reader; Writer }. - Struct in struct — promote fields/methods of a helper (an
Auditblock, async.Mutex). Embeddingsync.MutexpromotesLock/Unlockinto your type's public API, so any caller can lock your internals — usually you want a named, unexported fieldmu sync.Mutexinstead. - Interface in struct — the struct satisfies the interface by delegating to whatever value is stored, and can override individual methods. Great for decorators and partial fakes; calling a non-overridden method on a nil embedded interface panics.
Decorator — add logging/metrics around any authorizer without touching it:
type loggingAuthorizer struct {
next PaymentAuthorizer
log *slog.Logger
}
func WithLogging(next PaymentAuthorizer, log *slog.Logger) PaymentAuthorizer {
return loggingAuthorizer{next: next, log: log}
}
func (l loggingAuthorizer) Authorize(ctx context.Context, req AuthRequest) (AuthResult, error) {
start := time.Now()
res, err := l.next.Authorize(ctx, req)
l.log.InfoContext(ctx, "psp authorize",
"order_id", req.OrderID,
"duration_ms", time.Since(start).Milliseconds(),
"err", err)
return res, err
}
Note that WithLogging returns the interface: decorators are the legitimate exception to "return structs", because their whole point is substitutability.
Partial fake via interface embedding — override one method of a large SDK-shaped interface:
// flakyGateway fails the first n Capture calls, delegates everything else.
type flakyGateway struct {
Gateway // embedded interface: all other methods delegate
n int
}
func (f *flakyGateway) Capture(ctx context.Context, id string) error {
if f.n > 0 {
f.n--
return ErrTimeout
}
return f.Gateway.Capture(ctx, id)
}
Accept interfaces, return structs
- Accept interfaces: a function parameter typed as
io.Readerworks with files, HTTP bodies, gzip streams andstrings.Readerin tests. Ask for the least you need. - Return structs:
NewClient(...) *Clientlets callers use every method, embed it, or define their own narrow interface over it. Returning an interface forces you to grow the interface whenever you add a method and hides useful fields.
Exceptions, all deliberate: error (always return the interface type); decorators and middleware; factories that choose an implementation at runtime (hash.Hash from sha256.New()); and sealed/unexported implementations where you want to hide the concrete type.
io.Reader / io.Writer as the model
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
Read may return n > 0 and an error (including io.EOF) — process the n bytes first. The caller owns the buffer, so readers can be implemented without allocating.
Because the contract is tiny, stream stages compose. A daily settlement file can be decompressed, size-limited, hashed and uploaded in one pass with constant memory:
package settlement
import (
"compress/gzip"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
)
const maxFileSize = 2 << 30 // 2 GiB after decompression
var ErrTooLarge = errors.New("settlement: file exceeds size limit")
// Ingest decompresses src, writes it to dst, and returns the SHA-256 of the
// plaintext so it can be recorded for audit and duplicate detection.
func Ingest(dst io.Writer, src io.Reader) (digest string, size int64, err error) {
zr, err := gzip.NewReader(src)
if err != nil {
return "", 0, fmt.Errorf("open gzip: %w", err)
}
defer zr.Close()
h := sha256.New()
limited := io.LimitReader(zr, maxFileSize+1)
size, err = io.Copy(io.MultiWriter(dst, h), limited)
if err != nil {
return "", size, fmt.Errorf("copy: %w", err)
}
if size > maxFileSize {
return "", size, ErrTooLarge
}
return hex.EncodeToString(h.Sum(nil)), size, nil
}
The same function works with an S3 object body, a local file, or a bytes.Buffer in a unit test — that is the payoff of accepting interfaces. The limit also protects against decompression bombs.
The cost of interfaces
- A method call through an interface is an indirect call that the compiler usually cannot inline.
- Assigning a non-pointer value to an interface may allocate ("boxing"), and passing values through interface parameters often makes them escape to the heap (see Memory, GC & Escape Analysis).
- Profile-guided optimisation (GA in Go 1.21) can devirtualize hot interface calls when the profile shows one dominant concrete type.
At service boundaries (repositories, gateways) this cost is noise next to a network round trip. In a tight loop over a million ledger entries, prefer concrete types or generics.
Trade-offs
| Option | Strengths | Weaknesses | Choose when |
|---|---|---|---|
| Concrete type parameter | Inlinable, discoverable, no indirection | Hard to substitute in tests | One implementation, hot paths |
| Small consumer-defined interface | Decoupled, trivial fakes, clear dependency | One more name; indirection | Ports to I/O: PSPs, repos, clocks, queues |
| Large producer-defined interface | One place to look | Fakes are painful; every consumer coupled to every method | Rarely — plugin systems with a fixed contract |
| Embedding (struct or interface) | Little boilerplate, promoted methods | Leaks the embedded API; shadowing surprises | Decorators, partial fakes, small helpers |
| Explicit delegation (named field) | Precise API, nothing leaks | More code | Exported types where API surface matters |
| Type switch over sealed interface | Closed set, exhaustive handling | Adding a variant touches every switch | Domain events, commands |
| Generics instead of interface | Static dispatch, type-safe containers | More complex signatures | Data structures and algorithms, not behaviour |
In practice
A checkout service wired by hand in main, with a fake for tests:
// main.go — the only place that knows concrete types.
psp := stripe.New(cfg.StripeKey, &http.Client{Timeout: 10 * time.Second})
svc := checkout.NewService(
checkout.WithLogging(psp, logger),
postgres.NewOrderStore(pool),
)
// checkout_test.go
type fakeAuthorizer struct {
result AuthResult
err error
calls []AuthRequest
}
func (f *fakeAuthorizer) Authorize(_ context.Context, req AuthRequest) (AuthResult, error) {
f.calls = append(f.calls, req)
return f.result, f.err
}
Guidelines that hold up in code review:
- Name single-method interfaces after the method plus "-er":
Authorizer,Clock,Publisher. - Put
context.Contextfirst in every I/O method of a port; it is part of the contract. - Don't export an interface from the adapter package "for mocking" — let the consumer define it.
- Prefer hand-written fakes for ports with 1–3 methods; reach for generated mocks (
gomock,mockery) only when you must assert call order or arguments on wide interfaces (see Testing & Benchmarking). - Use
fmt.Stringerandslog.LogValuerinterfaces to control how domain types print — e.g. aCardNumbertype whoseLogValuereturns only the last four digits keeps PANs out of logs, which matters for PCI DSS.
Common pitfalls
- Typed nil in an interface —
return myErrPtrwhere the pointer is nil. Symptom:err != nilon success paths, error messages like<nil>. - Interface pollution — an interface per struct, declared in the producer package, with one implementation. Symptom: navigation pain, mocks everywhere, no real decoupling.
- Unchecked type assertion —
v := x.(T)in request handling panics on unexpected input. Use comma-ok. - Asserting on wrapped errors —
err.(*NotFoundError)fails once someone addsfmt.Errorf("...: %w", err). Useerrors.As. - Wrapping hides capabilities — your middleware's
ResponseWriterwrapper breaks streaming (Flusher) or HTTP/2 push detection. ImplementUnwrapand usehttp.NewResponseController. - Comparing
anyvalues holding slices/maps — runtime panic "comparing uncomparable type". - Embedding a mutex in an exported struct — callers can lock your internals.
- Pointer-receiver methods, value stored —
var a Authorizer = Client{}fails to compile when methods are on*Client; people then "fix" it by switching receivers and introduce copies.
Interview angle
Expect: "How are interfaces implemented in Go?", "Why does this function return a non-nil error?", "Where should interfaces be declared?", "How would you abstract several payment providers?", "What's the difference between embedding and inheritance?"
A strong answer explains the (itab, data) representation and the nil trap; says interfaces belong to consumers; uses io.Reader as the example of a small, composable contract; and connects interfaces to dependency inversion and testability. For the multi-PSP question, describe a narrow port (Authorize, Capture, Refund — possibly separate interfaces), per-provider adapters that map provider errors to domain errors, decorators for logging/metrics/retry, and routing logic in the core that picks a provider.
Follow-ups: "How do you handle a feature only one provider supports?" (optional capability interface + type assertion, or a separate port), "Cost of interface calls?", "When would you return an interface?"
Red flags: declaring interfaces before there's a second implementation "for flexibility", mocks of everything, or not knowing why err != nil can be true for a nil pointer.
Self-check
1. Draw the two words of an interface value and explain when x == nil is true.
Word one points to the itab (dynamic type and method table) or, for any, to the type descriptor; word two points to the data. x == nil only when both are nil — i.e. nothing was ever assigned. Storing a nil *T sets the type word, so the interface is non-nil.
2. Why should the checkout package, not the stripe adapter package, define PaymentAuthorizer?
The consumer knows which methods it needs, so it can keep the interface minimal; the dependency arrow then points from adapter to core (dependency inversion); and multiple adapters plus fakes satisfy it without importing anything shared. The adapter just exports a concrete *Client.
3. Your logging middleware wraps http.ResponseWriter, and server-sent events stop streaming. Why, and how do you fix it?
The SSE handler type-asserts w.(http.Flusher), but your wrapper type doesn't have a Flush method, so the assertion fails or flushing is skipped. Implement Unwrap() http.ResponseWriter on the wrapper and use http.NewResponseController(w).Flush() (Go 1.20+), or forward Flush explicitly.
4. Give three legitimate cases for a function returning an interface instead of a struct.
Returning error; decorators/middleware that must be substitutable for what they wrap; factories that select an implementation at runtime or hide unexported implementations (sha256.New() returns hash.Hash). Outside these, return the concrete type.
5. How does embedding differ from inheritance? Give a case where the difference causes a bug.
Embedding promotes methods, but the receiver is always the embedded value; there is no dynamic dispatch back to the outer type. If Base.Process() calls b.Validate() and Outer defines its own Validate, Outer.Process() still calls Base.Validate — engineers expecting template-method overriding get the base behaviour silently.
6. Scenario: a 1.5 GB gzip reconciliation file must be stored and fingerprinted. Sketch the I/O pipeline and its memory profile.
gzip.NewReader(body) then io.LimitReader then io.Copy(io.MultiWriter(objectStore, sha256)). Memory stays roughly constant (copy buffer of ≈32 KB plus gzip window) regardless of file size; you get the digest for duplicate detection and audit in the same pass, and the limit defends against decompression bombs.
7. When would you replace an interface parameter with a generic type parameter?
When the function is about the shape of data (containers, algorithms over cmp.Ordered, a typed cache) rather than behaviour of an external dependency, or when profiling shows interface dispatch/boxing in a hot loop. Ports to I/O should stay interfaces.
Exercise
Build a multi-provider payment port:
- In package
checkout, defineAuthorizerandRefunderinterfaces and aRouterthat selects a provider by currency (VND → domestic switch fake, USD → card processor fake). - Write two adapters with different native error types; map them to domain errors (
ErrDeclined,ErrProviderUnavailable) inside the adapters. - Add a
WithRetry(next Authorizer, attempts int)decorator that retries onlyErrProviderUnavailable, and aWithLoggingdecorator. Stack them inmain. - Add a compile-time assertion for each adapter and a test that reproduces the typed-nil bug, then fix it.
- Write
Ingestfrom this page and test it with abytes.Bufferholding a gzip of a fake CSV, plus a test that exceeds the size limit.
Done when: tests use only hand-written fakes, no package imports a vendor SDK except its adapter, and go vet ./... passes.
Further reading
- Effective Go — "Interfaces and other types", "Embedding".
- Go blog: "The Laws of Reflection" (Rob Pike) — interface representation.
- Russ Cox, "Go Data Structures: Interfaces" (research!rsc blog) — itabs explained.
- Go FAQ: "Why is my nil error value not equal to nil?"
- Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them — interface pollution, producer-side interfaces, returning interfaces.
iopackage documentation — the Reader/Writer contracts, including then > 0with error rule.- Robert C. Martin, Clean Architecture — dependency inversion, which Go interfaces implement without frameworks.
Related
- Go Fundamentals — method sets and receivers decide interface satisfaction.
- Error Handling — errors are the most common interface you return.
- Generics — the static alternative for data-shaped abstractions.
- Project Layout & Clean Architecture in Go — ports and adapters at module scale.
- SOLID in Go — interface segregation and dependency inversion.
- Design Patterns That Matter — decorator, adapter, strategy in Go form.
- Payments & Card Flows — what the authorizer and capturer actually do.
Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).