Adapter
An adapter is a type that exposes the interface you need by wrapping a type you already have. In Go that is a struct with an embedded or named field and methods that forward, translate, or both.
Detailed Explanation
http.HandlerFunc is an adapter: a function type with a ServeHTTP method so a function satisfies http.Handler. strings.NewReader adapts a string to io.Reader. You write the same thing when a vendor client has Fetch(id string) and your code wants Find(ctx, id).
Embedding vs wrapping. If the method names already match, embedding the inner type promotes the methods and you have an adapter with no extra code — and you may export more methods than you meant. A named field plus explicit methods is the adapter that translates names, adds ctx, and hides extra methods.
Direction. The adapter implements your interface. The inner type can be a concrete struct, another interface, or a function. Implicit satisfaction means you never declare implements. A compile-time var _ Store = (*VendorAdapter)(nil) documents the intent.
What it costs. One type and a few forwarding methods. That is cheaper than changing every call site when the vendor SDK changes. Do not adapt through any and reflection; write the methods.
Code Examples
package main
import (
"context"
"io"
"strings"
)
type Store interface {
Find(ctx context.Context, id string) (string, error)
}
type vendor struct{}
func (vendor) Fetch(id string) (string, error) { return id, nil }
type vendorAdapter struct{ inner vendor }
func (a vendorAdapter) Find(_ context.Context, id string) (string, error) {
return a.inner.Fetch(id)
}
var _ Store = vendorAdapter{}
func main() {
var r io.Reader = strings.NewReader("ok")
_, _ = r.Read(make([]byte, 2))
}Common Gotchas
An adapter that ignores `ctx` cannot be cancelled
pass it through or honour `ctx.Done()` around the inner call.
Adapters are not inheritance
they are a struct that sits in front of another value.