Interfaces, Type Assertions, Type Switches & any
"A Go type implements an interface by implementing the methods of that interface, nothing more." — The Go FAQ, Why doesn't Go have "implements" declarations? (go.dev/doc/faq, read with the Go 1.27 toolchain)
Summary: An interface is a set of methods; any type whose method set contains them satisfies it without saying so, and an interface value is a two-word pair (type, data) that you can inspect with type assertions and type switches. Focus: Method sets and implicit satisfaction, small interfaces (io.Reader, io.Writer, fmt.Stringer, error), accept interfaces / return structs, consumer-defined interfaces, the itab/data representation, the nil-interface vs nil-pointer bug, assertions and their panic texts, type switches, any and JSON, embedding, optional interfaces (http.Flusher, io.WriterTo), comparability, pointer receivers, dispatch cost, generics vs interfaces, errors.As, sort.Interface vs slices.SortFunc. Learning goal: Design the smallest interface the consumer needs, predict when an interface is nil, when an assertion panics and when a comparison panics, and choose between a concrete type, an interface, a type parameter and any.
This page owns Go interfaces as a language and runtime mechanism. It does not re-teach three neighbours: how methods attach to structs and how struct embedding promotes them is in Structs, Methods, Constructors, Embedding & Struct Tags; type parameters and constraints are in Generics; and how to build fakes, inject dependencies and use testify is in Mocking with Interfaces, Dependency Injection for Testability, testify. Error wrapping itself is in Errors, Wrapping, Panic, Recover & Defer, encoding/json in JSON, XML, Struct Tags, the io family in The io Package and run-time type inspection in reflect: When and How.
Page map
| If you are looking for | Go to |
|---|---|
| Tables to memorise in one minute | Everything in one minute |
| Why Go chose implicit interfaces | Why it exists |
| Spec, FAQ, Russ Cox 2009, Go 1.18 type sets | Where it comes from |
| "Does my type implement it?", pointer receivers | Method sets and implicit satisfaction |
io.Reader, fmt.Stringer, error, one-method interfaces | Small interfaces |
| Where to declare the interface | Accept interfaces, return structs |
| What an interface variable holds (itab, data) | Interface values |
err != nil although nothing failed | Nil interface vs interface holding a nil pointer |
x.(T), comma-ok, interface conversion panics | Type assertions |
switch v := x.(type), case nil, multi-type cases | Type switches |
any, interface{}, map[string]any, float64 numbers | any and the empty interface |
io.ReadWriteCloser, composing interfaces | Interface embedding |
http.Flusher, io.WriterTo, ResponseController | Optional interfaces |
| Interfaces as map keys, uncomparable panics | Comparable interfaces |
| Interface pollution, mocks | Interface pollution |
| Dispatch cost, heap escape, devirtualisation | Mechanics |
errors.As, sort.Interface vs slices.SortFunc, generics | Solving the classic problems |
| Concrete type, interface, generic or any | Choosing |
| Interfaces across modules and services | In architecture |
| Commands with real output | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The pieces. Each row is unpacked in the concept catalogue.
| Piece | In plain words | Tiny example | Trap |
|---|---|---|---|
| Interface type | A list of methods (a type set) | type Stringer interface{ String() string } | Big interfaces are hard to satisfy and to fake |
| Method set | The methods callable on a type | *T has T and *T methods; T only T methods | Counter is not an io.Writer if Write has a pointer receiver |
| Implicit satisfaction | No implements keyword | *os.File is an io.Reader because it has Read | Renaming a method silently breaks satisfaction elsewhere |
| Interface value | Two words: type information and data | var r io.Reader = f stores (*os.File, f) | Holding a nil pointer makes it non-nil |
| Type assertion | Pull the concrete value (or another interface) out | s, ok := v.(string) | Single-result form panics |
| Type switch | Branch on the dynamic type | switch x := v.(type) { case int: … } | Multi-type case keeps x as the interface type |
any | Alias for interface{} since Go 1.18 | func Log(attrs ...any) | Erases types; every use needs an assertion |
| Embedding | Interfaces built from interfaces | io.ReadWriteCloser | Embedding an interface in a struct hides extra methods |
| Optional interface | Check at run time for an extra ability | if wt, ok := r.(io.WriterTo); ok | Wrappers hide the ability |
| Comparability | == on interfaces compares type and value | any(1) == any(1) is true | Same uncomparable dynamic type panics |
The run-time failures you will meet.
| Code | Exact text | Cause |
|---|---|---|
v.(string) with v holding 42 | panic: interface conversion: interface {} is int, not string | Wrong concrete type, single-result assertion |
v.(string) with v == nil | interface conversion: interface {} is nil, not string | Asserting on a nil interface |
r.(io.Closer) on *strings.Reader | interface conversion: *strings.Reader is not io.Closer: missing method Close | Interface assertion, method missing |
any([]int{1}) == any([]int{1}) | runtime error: comparing uncomparable type []int | Same uncomparable dynamic type |
m[any([]string{"x"})]++ | runtime error: hash of unhashable type []string | Uncomparable map key |
| Calling a method of a nil embedded interface | runtime error: invalid memory address or nil pointer dereference | Struct field of interface type left nil |
errors.As(err, nonPointer) | errors: target must be a non-nil pointer | Wrong target (vet catches most) |
The compile-time errors (Go 1.27 toolchain, captured in the lab).
| Code | Compiler says |
|---|---|
var _ io.Writer = Counter{} | Counter does not implement io.Writer (method Write has pointer receiver) |
var _ fmt.Stringer = Temp(1) | Temp does not implement fmt.Stringer (missing method String) |
r.(string) with r io.Reader | impossible type assertion: r.(string) / string does not implement io.Reader (missing method Read) |
case int, int: | duplicate case int in type switch |
Why it exists
Code needs to say "give me anything that can do X" without knowing every type that can. Class-based languages answer with explicit declarations: a class says implements Reader, and only declared classes qualify. Go decided that the declaration is the problem: a package written in 2012 cannot declare that it implements an interface invented in 2024. In Go the consumer writes down the methods it needs, and every type that already has those methods qualifies, including types from packages that have never heard of the interface. The price is that satisfaction is invisible in the source, and that an interface value carries run-time type information that you can (and sometimes must) inspect.
| Explicit nominal interfaces (PHP, Java, C#) | Implicit structural interfaces (Go) |
|---|---|
The implementer names the interface: class File implements Reader | The consumer names the methods; satisfaction is automatic |
| Interfaces live with the implementation or a shared contracts package | Interfaces live with the consumer, often unexported |
| Adding a method to an interface breaks every implementer at once, visibly | Adding a method breaks implementers wherever they are assigned, at compile time |
| You cannot make a third-party class implement your interface without an adapter | Any type with the right methods already implements it |
| Big "service" interfaces are normal | One- and two-method interfaces are normal |
instanceof checks the declared hierarchy | Type assertions check the method set at run time |
The analogy we reuse on this page: a power socket. The socket on the wall (the interface) does not care which factory made your device; it only cares that the plug has the right pins (the methods). A device never registers with the socket company. An interface value is the plug in the wall: one wire says what device it is (the type word), the other carries the current to it (the data word). A plug with a dead device on the end (a nil pointer) is still a plug in the socket — the socket is not empty. An adapter strip that only passes two pins (a wrapper that embeds only http.ResponseWriter) hides the third pin your device needed (Flush).
Three common misunderstandings, up front
- "An interface holding nil is nil." It is not.
var p *MyErr; var err error = pstores the type*MyErr, soerr != nil. Only an interface with no type and no value is nil. - "Define the interface next to the implementation so others can mock it." Go's own review guide says the opposite: interfaces belong to the package that uses them, and the implementation should return a concrete type.
- "Generics replaced
interface{}and interfaces." Generics replaced some uses ofany. If all you do is call methods, an interface is still the answer, and a type parameter is usually not faster.
Where it comes from
Interfaces have been in Go since the public release in November 2009. Russ Cox's post Go Data Structures: Interfaces (1 December 2009) explained the implementation and called them "static, checked at compile time, dynamic when asked for"; it describes interface values as "a two-word pair giving a pointer to information about the type stored in the interface and a pointer to the associated data", the first word pointing at "an interface table or itable". The post notes that Go's interfaces let you use duck typing "like you would in a purely dynamic language like Python but still have the compiler catch obvious mistakes". (research.swtch.com refuses automated fetches from this machine; the text was read from the Internet Archive copy listed in References.)
The Go FAQ answers "Why doesn't Go have implements declarations?" with the opening quote and adds that the property "enables a kind of structural typing that promotes separation of concerns and improves code re-use". Rob Pike's Go Proverbs (2015) compressed the design advice into "The bigger the interface, the weaker the abstraction." and "interface{} says nothing." Rob Pike's The Laws of Reflection (2011) described the interface variable as storing "the concrete value assigned to the variable, and that value's type descriptor".
Go 1.18 (March 2022) rewrote the specification's model: "An interface type defines a type set." Interfaces may now also list types and unions (~int | ~float64), but such non-basic interfaces "may only be used as type constraints". The same release added any — "For convenience, the predeclared type any is an alias for the empty interface; it is not a named type." — and the predeclared comparable constraint. Go 1.20 let comparable be satisfied by interface types ("comparison may panic at runtime") and added http.ResponseController. Go 1.21 added the generic slices package (slices.SortFunc) and PGO-based devirtualisation: "PGO builds can now devirtualize some interface method calls, adding a concrete call to the most common callee." Go 1.26 added errors.AsType, "a generic version of As". Go 1.27 (August 2026) added generic methods on concrete types and kept the rule that "methods of interfaces may not declare type parameters nor can interface methods be implemented by generic methods". The snippet module targets go 1.24 and was tested with the Go 1.27.4 toolchain.
The concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, behaviour per case, and the fix in Go (full code in Solving the classic problems).
Method sets and implicit satisfaction Must-know
In plain words: a type satisfies an interface when its method set contains every method of the interface, with identical names and signatures. Nobody declares it. Whether T or *T is the one that satisfies depends on the receivers.
Common misunderstanding: "If I can call c.Write(p) on my Counter variable, then Counter is an io.Writer." You can call it because the variable is addressable and Go rewrites the call to (&c).Write(p). A value copied into an interface is not addressable, so only *Counter satisfies io.Writer. The FAQ explains why: "if an interface value contains a value T, there is no safe way for a method call to obtain a pointer."
Definition: the spec: "The method set of a defined type T consists of all methods declared with receiver type T. The method set of a pointer to a defined type T (where T is neither a pointer nor an interface) is the set of all methods declared with receiver *T or T." A type T implements interface I if "T is not an interface and is an element of the type set of I". This is structural typing checked at compile time — the static cousin of duck typing.
1 type Counter struct{ N int }
2 func (c *Counter) Write(p []byte) (int, error) // pointer receiver
3 method set of Counter = { } // no value methods
4 method set of *Counter = { Write }
5 var w io.Writer = &c -> compiles: *Counter ∈ type set of io.Writer
6 var w io.Writer = c -> compile error: method Write has pointer receiver
7 var _ io.Writer = (*Counter)(nil) -> compile-time assertion, zero costReal scenario: a payments package renames Charge(ctx, amt) to Charge(ctx, amt, idemKey); every place that assigned the client to the old Charger interface fails to compile, which is good, but a place that only stored it in any and asserted later fails at run time. A cache type with func (c *Cache) Get passed by value to NewHandler(c) does not compile; the fix is &c, not changing the receiver. A Temperature float64 with a value-receiver String() prints nicely in fmt.Println both as value and pointer.
| Receiver of the methods | T satisfies? | *T satisfies? | Typical reason |
|---|---|---|---|
| All value receivers | Yes | Yes | Small immutable types: time.Duration, Celsius |
| All pointer receivers | No | Yes | Mutating types or types with a mutex: *bytes.Buffer, *Counter |
| Mixed | Only if the interface's methods are all value methods | Yes | Usually a smell; pick one receiver kind per type |
Interface type I | Yes, if its method set is a superset | Pointers to interfaces have no methods | Never use *io.Reader |
Fix / how to use it: keep receivers consistent per type (structs and methods covers the choice); pass &v to interface parameters when methods mutate; add var _ I = (*T)(nil) next to the type when satisfaction is part of its contract (the FAQ's own recipe).
// Package methodset shows implicit satisfaction and the pointer-receiver rule.
package methodset
import (
"fmt"
"io"
)
// Celsius has a value-receiver String method, so both Celsius and *Celsius
// are fmt.Stringer.
type Celsius float64
func (c Celsius) String() string { return fmt.Sprintf("%.1f°C", float64(c)) }
// Counter has a pointer-receiver Write method: only *Counter is an io.Writer.
// Counter (the value type) is not, because a value stored in an interface
// is not addressable.
type Counter struct{ N int }
func (c *Counter) Write(p []byte) (int, error) {
c.N += len(p)
return len(p), nil
}
// Compile-time assertions: the build fails if a method is renamed or its
// signature drifts. Nothing is allocated at run time.
var (
_ fmt.Stringer = Celsius(0)
_ fmt.Stringer = (*Celsius)(nil)
_ io.Writer = (*Counter)(nil)
// _ io.Writer = Counter{} // does not compile:
// cannot use Counter{} (value of struct type Counter) as io.Writer value
// in variable declaration: Counter does not implement io.Writer
// (method Write has pointer receiver)
)
// Describe accepts the smallest interface it needs.
func Describe(s fmt.Stringer) string { return "value=" + s.String() }
// CountBytes writes through any io.Writer; *Counter happens to be one.
func CountBytes(w io.Writer, parts ...string) error {
for _, p := range parts {
if _, err := io.WriteString(w, p); err != nil {
return err
}
}
return nil
}Small interfaces: io.Reader, io.Writer, fmt.Stringer, error Must-know
In plain words: the most useful Go interfaces have one method. io.Reader is "something you can read bytes from", io.Writer "something you can write bytes to", fmt.Stringer "something that can print itself", error "something that can describe a failure".
Common misunderstanding: "A one-method interface is too thin to be worth naming." It is the opposite: Effective Go notes that "Interfaces with only one or two methods are common in Go code, and are usually given a name derived from the method, such as io.Writer". The smaller the interface, the more types satisfy it and the cheaper it is to fake.
Definition:
| Interface | Package | Method | Implemented by (examples) |
|---|---|---|---|
io.Reader | io | Read(p []byte) (n int, err error) | *os.File, *strings.Reader, *bytes.Buffer, net.Conn, *gzip.Reader, http.Request.Body |
io.Writer | io | Write(p []byte) (n int, err error) | *os.File, *bytes.Buffer, http.ResponseWriter, *bufio.Writer, hash.Hash |
io.Closer | io | Close() error | files, connections, response bodies |
fmt.Stringer | fmt | String() string | time.Duration, net.IP, your enums |
error | predeclared | Error() string | *os.PathError, *net.OpError, your error types |
sort.Interface | sort | Len, Less, Swap | sort.IntSlice, your slice types |
http.Handler | net/http | ServeHTTP(ResponseWriter, *Request) | http.HandlerFunc, *http.ServeMux |
1 gzip.NewReader(f) f is *os.File -> accepted as io.Reader
2 io.Copy(hash, gz) hash is hash.Hash -> accepted as io.Writer
3 io.Copy(w, gz) w is ResponseWriter -> accepted as io.Writer
4 one function (io.Copy) composes three unrelated packages through two one-method interfacesReal scenario: an upload handler streams r.Body through sha256.New() and into S3 with no buffering because all three speak io.Reader/io.Writer. A Status enum implements String() so logs show paid instead of 3. An exporter writes CSV to io.Writer, so the same code writes to a file, an HTTP response and a bytes.Buffer in the test. Pike's proverb, "The bigger the interface, the weaker the abstraction", is the design rule.
Fix / how to use it: take io.Reader instead of *os.File or a filename; implement String() on enums; keep your own interfaces to the methods one caller actually uses. Composition is in The io Package.
Accept interfaces, return structs; consumer-defined interfaces Must-know
In plain words: functions take the smallest interface they need as a parameter and return a concrete type. The interface is declared in the package that calls the methods, not in the package that implements them.
Common misunderstanding: "Every service needs an exported UserRepository interface next to its implementation, so callers can mock it." The Go Code Review Comments say: "Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values. The implementing package should return concrete (usually pointer or struct) types". And: "Do not define interfaces on the implementor side of an API 'for mocking'".
Definition: "accept interfaces, return structs" (often searched as "accept interfaces return structs") is a community proverb, not a spec rule, but it follows directly from the review guide. Returning a concrete type lets the implementer add methods without breaking anyone; accepting an interface lets the caller pass any implementation (real, fake, decorator). Effective Go lists the exception: when a type "exists only to implement an interface", the constructor may return the interface (crc32.NewIEEE returns hash.Hash32).
1 package store: func NewStore() *Store // concrete, 3 exported methods
2 package notify: type emailLookup interface{ Email(ctx, id) (string, error) } // unexported, 1 method
3 package notify: func NewNotifier(u emailLookup, s Sender) *Notifier
4 package main: notify.NewNotifier(store.NewStore(), smtpSender) // *Store satisfies emailLookup implicitly
5 notify_test.go: notify.NewNotifier(fakeLookup{1: "a@example.com"}, SenderFunc(...))
6 store adds a 4th method -> nobody breaks; notify never imported storeReal scenario: a notification module needs one lookup from a 40-method user service: it declares a one-method interface and the test fake is 6 lines. A billing package returns *Client; three consumers each declare the two methods they use. A Laravel developer's habit of interface UserRepositoryInterface per class produces a Go codebase where every change to a struct must be mirrored in an interface nobody else implements.
| Style | Where the interface lives | Who breaks when a method is added | Fake size |
|---|---|---|---|
| Producer-side exported interface | Next to the implementation | Every fake and every other implementation | Whole interface |
| Consumer-defined interface | Next to the caller | Nobody (the consumer only lists what it uses) | 1–3 methods |
| Standard-library interface | io, fmt, net/http | Nobody | Tiny |
| Function type adapter | type SenderFunc func(...) with a method | Nobody | A closure |
Fix / how to use it: declare the interface where it is used, unexported if only one package uses it; return *Store, not StoreInterface; offer a Func adapter (like http.HandlerFunc) for one-method interfaces. Building fakes and DI wiring are in Mocking with Interfaces; the principle behind it is Interface Segregation and Dependency Inversion.
// Package consumer shows "accept interfaces, return structs" with the
// interface declared by the code that uses it.
package consumer
import (
"context"
"errors"
"fmt"
"sync"
)
// --- producer side (would normally live in package store) ---
// Store is a concrete type. It exports many methods; nobody needs all of them.
type Store struct {
mu sync.Mutex
users map[int64]string
}
// NewStore returns the concrete *Store, not an interface.
func NewStore() *Store { return &Store{users: map[int64]string{}} }
// ErrNotFound is returned when a user does not exist.
var ErrNotFound = errors.New("not found")
func (s *Store) Put(_ context.Context, id int64, email string) error {
s.mu.Lock()
defer s.mu.Unlock()
s.users[id] = email
return nil
}
func (s *Store) Email(_ context.Context, id int64) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
e, ok := s.users[id]
if !ok {
return "", ErrNotFound
}
return e, nil
}
func (s *Store) Delete(_ context.Context, id int64) error {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.users, id)
return nil
}
// --- consumer side (package notify) ---
// emailLookup is the one method Notifier needs. It is unexported and lives
// next to its only user; *Store satisfies it without knowing it exists.
type emailLookup interface {
Email(ctx context.Context, id int64) (string, error)
}
// Sender is the second dependency, also as small as possible.
type Sender interface {
Send(ctx context.Context, to, body string) error
}
// Notifier is returned as a concrete struct pointer.
type Notifier struct {
users emailLookup
out Sender
}
// NewNotifier accepts interfaces and returns a struct.
func NewNotifier(users emailLookup, out Sender) *Notifier {
return &Notifier{users: users, out: out}
}
func (n *Notifier) Welcome(ctx context.Context, id int64) error {
to, err := n.users.Email(ctx, id)
if err != nil {
return fmt.Errorf("welcome %d: %w", id, err)
}
return n.out.Send(ctx, to, "welcome")
}
// SenderFunc adapts a plain function to Sender, like http.HandlerFunc.
type SenderFunc func(ctx context.Context, to, body string) error
func (f SenderFunc) Send(ctx context.Context, to, body string) error { return f(ctx, to, body) }Interface values: itab, dynamic type, dynamic value Must-know
In plain words: a variable of interface type holds two hidden words: one says which concrete type is inside, the other points at the value. The interface type you declared is the static type; the type inside is the dynamic type.
Common misunderstanding: "Assigning to an interface just copies a pointer." It copies the value: if you put a struct into an interface and then change the original, the interface still holds the old copy. And values that do not fit in one word usually go to the heap.
Definition: the FAQ: "interfaces are implemented as two elements, a type T and a value V. V is a concrete value such as an int, struct or pointer, never an interface itself". In the gc runtime (runtime/runtime2.go) a non-empty interface is iface{tab *itab; data unsafe.Pointer} and an empty interface is eface{_type *_type; data unsafe.Pointer}. The itab (internal/abi.ITab) holds Inter, Type, Hash ("Used for type switches") and Fun, the method pointers. The runtime builds an itab the first time a (interface, concrete type) pair is needed and caches it; Cox: "The runtime caches the itable after generating it, so that this correspondence need only be computed once."
1 var s fmt.Stringer s = (tab=nil, data=nil) s == nil
2 s = Celsius(21.5) tab -> itab{Stringer, Celsius, fun[0]=Celsius.String}
3 data -> heap copy of 21.5
4 s.String() load s.tab.fun[0], call it with s.data (dynamic dispatch)
5 var v any = s v = (_type=Celsius, data=same pointer) (eface, no itab)
6 w := v.(fmt.Stringer) runtime looks up / caches itab{Stringer, Celsius}Real scenario: a []any of a million float64 values costs two words per element plus a heap box per value — the reason []any result rows are slow. A logger taking ...any allocates for every non-pointer argument that escapes. fmt.Printf("%T", err) prints the dynamic type, which is the fastest way to debug "what is actually in this error?".
| Value stored | Data word | Allocation? |
|---|---|---|
| Pointer, map, chan, func (pointer-shaped) | The pointer itself | No |
| Small integers 0–255, single-byte values | Pointer into the runtime's static staticuint64s table | No |
| Zero-size value | Pointer to a shared zero-size base | No |
Other non-pointer values (float64, structs, strings) that escape | Pointer to a heap copy | Yes, unless escape analysis keeps it on the stack |
| Constant values known at compile time | Pointer to read-only data | No |
Fix / how to use it: store pointers in interfaces when the value is large or mutated; avoid []any on hot paths; use %T and %#v when debugging. Measurements are in Mechanics.
Nil interface vs interface holding a nil pointer Must-know
In plain words: an interface is nil only when it holds nothing at all. An interface holding nil pointer of some type (a nil *MyErr, say) still knows the type, so it is not nil.
Common misunderstanding: "return p where p is a nil *MyErr returns a nil error." It returns (type=*MyErr, value=nil), and every caller's if err != nil fires.
Definition: the FAQ: "An interface value is nil only if the V and T are both unset, (T=nil, V is not set)... If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (T=*int, V=nil). Such an interface value will therefore be non-nil even when the pointer value V inside is nil."
ValidateBuggy("a@example.com") caller
1 var verr *ValidationError // nil
2 email is fine, verr stays nil
3 return verr // converts to error: (T=*ValidationError, V=nil)
4 err := ValidateBuggy(...)
5 if err != nil { // TRUE
6 log.Printf("%v", err) // prints <nil>
7 return 400 // valid request rejectedReal scenario: a validation helper returns *ValidationError and the HTTP layer converts it to error: every valid request gets a 400 with body <nil>. A repository's findOrNil() *Row passed to a function returning error through an adapter. A gRPC interceptor that returns a typed *status.Status nil as error. errors.Is(err, nil) style checks that never match.
| Pattern | Result as error | Safe? |
|---|---|---|
return nil in a func returning error | nil interface | Yes |
var e *MyErr; return e | non-nil, holds nil pointer | No |
return helper() where helper returns *MyErr | non-nil when helper returned nil | No |
if e := helper(); e != nil { return e }; return nil | correct | Yes |
Comparing with reflect.ValueOf(err).IsNil() | Works but hides the design bug | Last resort |
Fix / how to use it: functions that can fail return error, never a concrete error type; return the literal nil on success; if a helper must return a concrete pointer, check it before converting. Methods with pointer receivers that handle a nil receiver are fine, but the interface is still non-nil. The same mechanism with plain variables is shown in typed nil.
// Package nilerror reproduces the "nil pointer inside a non-nil error" bug.
package nilerror
import "fmt"
// ValidationError is a custom error with a pointer receiver.
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return "invalid " + e.Field }
// ValidateBuggy returns *ValidationError typed as error. When the input is
// valid it returns a nil *ValidationError, which the caller sees as a
// non-nil error interface: (type=*ValidationError, value=nil).
func ValidateBuggy(email string) error {
var verr *ValidationError
if email == "" {
verr = &ValidationError{Field: "email"}
}
return verr // BUG: always non-nil as an error
}
// validateConcrete is the root cause in another shape: a helper that
// returns the concrete pointer type.
func validateConcrete(email string) *ValidationError {
if email == "" {
return &ValidationError{Field: "email"}
}
return nil
}
// ValidateWrapped shows the same bug through a helper.
func ValidateWrapped(email string) error {
return validateConcrete(email) // BUG: converts nil *ValidationError to error
}
// Validate is the fix: return the untyped nil literal on success, and
// declare the result as error, never as the concrete type.
func Validate(email string) error {
if email == "" {
return &ValidationError{Field: "email"}
}
return nil
}
// Describe prints the interface pair the way the runtime sees it.
func Describe(err error) string {
return fmt.Sprintf("err==nil:%t type:%T value:%v", err == nil, err, err)
}Type assertions and comma-ok Must-know
In plain words: x.(T) says "I believe the thing inside x is a T; give it to me as a T." With one result it panics if you are wrong; with two (v, ok := x.(T)) it tells you.
Common misunderstanding: "A type assertion converts the value." It does not convert anything: any(int32(5)).(int) fails because int32 is not int. It only checks the dynamic type (or, for an interface T, the dynamic type's method set).
Definition: the spec: "x.(T) asserts that x is not nil and that the value stored in x is of type T." If T is not an interface, "x.(T) asserts that the dynamic type of x is identical to the type T"; if T is an interface, it "asserts that the dynamic type of x implements the interface T". With the comma-ok form "The value of ok is true if the assertion holds. Otherwise it is false and the value of v is the zero value for type T. No run-time panic occurs in this case." If T is a concrete type that cannot implement x's static interface, it is a compile error (impossible type assertion).
1 var v any = 42
2 s, ok := v.(string) -> s == "", ok == false (no panic)
3 n := v.(int) -> n == 42
4 s := v.(string) -> panic: interface conversion: interface {} is int, not string
5 var r io.Reader = strings.NewReader("x")
6 c := r.(io.Closer) -> panic: interface conversion: *strings.Reader is not io.Closer: missing method Close
7 var e any // nil
8 e.(string) -> panic: interface conversion: interface {} is nil, not stringThe texts come from runtime.(*TypeAssertionError).Error, which also adds "(types from different packages)" when two types print the same name.
Real scenario: a middleware reads ctx.Value(userKey).(User) with one result, and a route that skipped auth crashes the whole request goroutine (recovered by net/http only for that request). encoding/json checks val.(json.Marshaler) at run time (Effective Go's "Interface checks" section). A plugin registry stores any and asserts to Plugin.
| Form | On mismatch | Use when |
|---|---|---|
v := x.(T) | Panic with interface conversion text | The type is an invariant you control; a panic is a bug report |
v, ok := x.(T) | ok == false, v is zero | Anything coming from outside: context values, any payloads, optional abilities |
x.(I) with interface I | Panic or false if a method is missing | Upgrading to an optional interface |
| Type switch | Falls to default | Three or more possible types |
errors.As(err, &target) | Returns false | Errors, which may be wrapped |
Fix / how to use it: default to comma-ok; use the single form only for programmer invariants; never assert on errors directly when they may be wrapped — use errors.As.
// Package assertswitch shows type assertions, comma-ok and type switches.
package assertswitch
import (
"fmt"
"io"
"strconv"
"time"
)
// MustString uses the single-result form: it panics when v is not a string.
func MustString(v any) string { return v.(string) }
// AsString uses the comma-ok form: it never panics.
func AsString(v any) (string, bool) {
s, ok := v.(string) // s is "" when ok is false
return s, ok
}
// Recover runs f and returns the panic message, or "" if f did not panic.
func Recover(f func()) (msg string) {
defer func() {
if r := recover(); r != nil {
msg = fmt.Sprint(r)
}
}()
f()
return ""
}
// Format renders an attribute value from a log or metrics pipeline.
// It shows: case nil, a single-type case (binding has that type),
// a multi-type case (binding keeps the interface type), an interface
// case (fmt.Stringer), and ordering (error before Stringer).
func Format(v any) string {
switch x := v.(type) {
case nil:
return "null"
case string:
return strconv.Quote(x) // x is string
case int, int64:
return fmt.Sprintf("int:%v", x) // x is any here
case float64:
return strconv.FormatFloat(x, 'f', -1, 64)
case bool:
return strconv.FormatBool(x)
case time.Duration: // must come before fmt.Stringer, Duration has String()
return "dur:" + x.String()
case error:
return "error:" + x.Error()
case fmt.Stringer:
return "str:" + x.String()
case []byte:
return fmt.Sprintf("bytes:%d", len(x))
default:
return fmt.Sprintf("other:%T", x)
}
}
// Closer upgrades a Reader to a ReadCloser only if the dynamic type has Close.
// Asserting to an interface type checks the method set at run time.
func Closer(r io.Reader) (io.Closer, bool) {
c, ok := r.(io.Closer)
return c, ok
}Type switches Must-know
In plain words: a type switch is a switch over the dynamic type. Each case names a type; the first case that matches runs, and the bound variable has that case's type.
Common misunderstanding: "In case int, int64: the variable is a number." When a case lists more than one type, the variable keeps the type of the switched expression (any), so you cannot do arithmetic on it. Another one: "cases are tried by specificity". They are tried in order, so case fmt.Stringer before case time.Duration swallows durations.
Definition: the spec: "A type switch compares types rather than values." With switch x := v.(type), "In clauses with a case listing exactly one type, the variable has that type; otherwise, the variable has the type of the expression in the TypeSwitchGuard." "Instead of a type, a case may use the predeclared identifier nil; that case is selected when the expression in the TypeSwitchGuard is a nil interface value. There may be at most one nil case." Cases may be interface types; duplicates are a compile error; "The fallthrough statement is not permitted in a type switch."
1 Format(1500*time.Millisecond)
2 case nil? no (type word is set)
3 case string? no
4 case int, int64? no
5 case float64? no
6 case bool? no
7 case time.Duration? YES -> x is time.Duration, returns "dur:1.5s"
8 (case fmt.Stringer would also match, but it is listed later and never reached)Real scenario: a structured logger renders attribute values (string, numbers, error, fmt.Stringer, nil); a JSON walker over map[string]any; an RPC error mapper switches on *NotFoundError, *ConflictError, default 500; a SQL driver's driver.Value conversion. net.IP is a named []byte, so it does not match case []byte but does match case fmt.Stringer — the test in the snippet proves it.
| Case form | Bound variable type | Matches |
|---|---|---|
case nil: | Static type of the expression | Only a nil interface (not a nil pointer inside) |
case T: (one concrete type) | T | Dynamic type identical to T |
case I: (one interface) | I | Dynamic type implements I |
case A, B: | Static type of the expression | Either |
default: | Static type of the expression | Anything else |
case P: (type parameter, generic code) | P | After instantiation; first duplicate wins |
Fix / how to use it: order specific concrete types before interfaces; put case nil first; keep one type per case when you need the typed variable; when the set of types is closed and yours, prefer a method on an interface over a type switch (adding a type then cannot forget a case).
any and the empty interface Must-know
In plain words: any is another name for interface{}: an interface with no methods, so every type satisfies it. It tells the compiler nothing about the value.
Common misunderstanding: "any is Go's mixed, use it for flexibility." Pike's proverb is blunt: "interface{} says nothing." Every any moves a compile-time check to a run-time assertion. A second one: "JSON numbers decode to int". Inside any they are always float64.
Definition: the spec: "all types implement the empty interface"; "the predeclared type any is an alias for the empty interface; it is not a named type" (Go 1.18). Because it is an alias, any and interface{} are the same type and interchangeable. The encoding/json documentation lists what Unmarshal stores in an interface value: "bool, for JSON booleans; float64, for JSON numbers; string, for JSON strings; []any, for JSON arrays; map[string]any, for JSON objects; nil for JSON null". Decoder.UseNumber changes numbers to json.Number, a string type that keeps all digits.
1 body: {"id":9007199254740993,"total":19.5}
2 json.Unmarshal(body, &v) v = map[string]any{"id": float64(9.007199254740992e15), ...}
3 v["id"].(int) -> ok == false (it is float64)
4 int64(v["id"].(float64)) -> 9007199254740992 (last digit lost: > 2^53)
5 dec.UseNumber(); dec.Decode(&v) v["id"] = json.Number("9007199254740993")
6 json.Unmarshal(body, &order) order.ID int64 = 9007199254740993 (typed struct: exact)Real scenario: a webhook with Snowflake-style 64-bit IDs decoded into map[string]any loses precision and the order lookup misses; v["qty"].(int) panics in production; a cache stores any and every reader asserts. Legitimate any: fmt.Println, slog attributes, context.WithValue values, json.Unmarshal targets, sql.Rows.Scan(dest ...any), sync.Map. The PostgreSQL side of the same payload:
-- the open-ended part lives in jsonb; the known fields get real columns
CREATE TABLE orders (
id bigint PRIMARY KEY,
total_cents bigint NOT NULL,
meta jsonb NOT NULL DEFAULT '{}'
);
SELECT id, meta->>'qty' AS qty, jsonb_typeof(meta->'qty') AS qty_type -- 'number', not int
FROM orders WHERE id = 9007199254740993;Use of any | Verdict | Better |
|---|---|---|
Formatting and logging (fmt, slog) | Fine | — |
| Decoding JSON of unknown shape | Fine at the edge | Convert to structs immediately; UseNumber for IDs |
| Function parameter "to be flexible" | Smell | A small interface or a type parameter |
Container of one element type ([]any of ints) | Smell | []int or a generic type |
| Map value in a cache | Smell | Generic Cache[K, V] |
context.Value | Fine with unexported key types | Typed accessor functions |
| Plugin payloads, event buses | Acceptable | Typed events, a type switch in one place |
Fix / how to use it: decode into structs (see JSON, XML, Struct Tags); keep map[string]any only for the truly open part; use UseNumber when integers matter; replace any containers with generics.
// Package jsonany decodes JSON into any and walks it with a type switch.
package jsonany
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
)
// Decode uses the default rules: numbers become float64.
func Decode(data []byte) (any, error) {
var v any
if err := json.Unmarshal(data, &v); err != nil {
return nil, err
}
return v, nil
}
// DecodeNumbers keeps numbers as json.Number (a string type) so large
// integers such as IDs keep every digit.
func DecodeNumbers(data []byte) (any, error) {
dec := json.NewDecoder(bytes.NewReader(data))
dec.UseNumber()
var v any
if err := dec.Decode(&v); err != nil {
return nil, err
}
return v, nil
}
// Walk prints every leaf as path=type:value, in a stable order.
func Walk(v any) []string {
var out []string
var walk func(path string, v any)
walk = func(path string, v any) {
switch x := v.(type) {
case map[string]any:
keys := make([]string, 0, len(x))
for k := range x {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
walk(path+"."+k, x[k])
}
case []any:
for i, e := range x {
walk(fmt.Sprintf("%s[%d]", path, i), e)
}
case nil:
out = append(out, path+"=null")
case float64, string, bool, json.Number:
out = append(out, fmt.Sprintf("%s=%T:%v", path, x, x))
default:
out = append(out, fmt.Sprintf("%s=unexpected %T", path, x))
}
}
walk("$", v)
return out
}
// Order is the typed alternative: decode into a struct when you know the shape.
type Order struct {
ID int64 `json:"id"`
Total float64 `json:"total"`
Meta map[string]any `json:"meta"` // the only truly open-ended part
}
// Summary is a helper for the lab.
func Summary(lines []string) string { return strings.Join(lines, "\n") }Interface embedding and composition Important
In plain words: you build bigger interfaces by listing smaller ones inside: io.ReadWriteCloser is io.Reader + io.Writer + io.Closer. A value of a wide interface converts to any narrower one automatically.
Common misunderstanding: "Embedding an interface in a struct is the same as embedding it in an interface." In a struct it declares a field of interface type; methods are promoted from whatever value you put there, and if you leave it nil, calling a promoted method panics with invalid memory address or nil pointer dereference. It also hides every other method of the wrapped value (see optional interfaces).
Definition: the spec: "The type set of T is the intersection of the type sets defined by T's explicitly declared methods and the type sets of T's embedded interfaces." Methods with the same name must have identical signatures (since Go 1.14 duplicates are allowed if identical). In the standard library: io.ReadWriter, io.ReadCloser, io.WriteCloser, io.ReadWriteCloser, io.ReadSeeker, io.ReadWriteSeeker.
1 type Conn interface { io.Reader; io.Writer; io.Closer } // method set {Read, Write, Close}
2 var c Conn = NewPipe()
3 var w io.Writer = c -> implicit: Conn's type set ⊂ io.Writer's type set
4 var c2 Conn = w -> compile error: io.Writer does not implement Conn (missing method Close)
5 c2, ok := w.(Conn) -> run-time check, ok == true hereReal scenario: a TLS wrapper takes net.Conn and returns net.Conn; os/exec exposes StdinPipe() (io.WriteCloser, error); a decorator struct embeds io.Writer and overrides only Write to count bytes; an http.ResponseWriter wrapper embeds the interface and loses Flush.
| Embedding | Effect | Pitfall |
|---|---|---|
| Interface in interface | Union of method sets | Name clash with different signature: compile error |
| Interface in struct | Field + promoted methods from the stored value | Nil field panics; hides extra methods |
| Struct in struct | Promotes fields and methods | Covered in structs |
Pointer to interface (*io.Reader) | Almost never what you want | Has no methods |
Fix / how to use it: compose public interfaces from one-method ones; in decorators, initialise the embedded interface in the constructor and forward or re-expose optional methods explicitly (or provide Unwrap).
// Package embedding composes small interfaces into larger ones.
package embedding
import (
"errors"
"io"
)
// Conn is composed exactly like io.ReadWriteCloser: the method set is the
// union of the embedded interfaces' method sets.
type Conn interface {
io.Reader
io.Writer
io.Closer
}
// PipeConn is an in-memory Conn used by tests and the lab.
type PipeConn struct {
buf []byte
closed bool
}
// ErrClosed is returned after Close.
var ErrClosed = errors.New("conn closed")
func (c *PipeConn) Write(p []byte) (int, error) {
if c.closed {
return 0, ErrClosed
}
c.buf = append(c.buf, p...)
return len(p), nil
}
func (c *PipeConn) Read(p []byte) (int, error) {
if len(c.buf) == 0 {
if c.closed {
return 0, io.EOF
}
return 0, nil
}
n := copy(p, c.buf)
c.buf = c.buf[n:]
return n, nil
}
func (c *PipeConn) Close() error { c.closed = true; return nil }
// NewPipe returns the concrete type; callers may store it in any of
// io.Reader, io.Writer, io.Closer, io.ReadWriteCloser or Conn.
func NewPipe() *PipeConn { return &PipeConn{} }
// Compile-time proof that the composite interfaces are satisfied.
var (
_ Conn = (*PipeConn)(nil)
_ io.ReadWriteCloser = (*PipeConn)(nil)
)
// Narrow shows that a wide interface converts implicitly to a narrower one
// (no assertion needed), but not the other way round.
func Narrow(c Conn) io.Writer { return c }
// CountingWriter embeds an interface in a STRUCT: it decorates Write and
// forwards everything else. Calling an unset embedded interface panics.
type CountingWriter struct {
io.Writer
N int
}
func (w *CountingWriter) Write(p []byte) (int, error) {
n, err := w.Writer.Write(p)
w.N += n
return n, err
}
// Counting wraps w.
func Counting(w io.Writer) *CountingWriter { return &CountingWriter{Writer: w} }Optional interfaces and the upgrade pattern Important
In plain words: a function accepts a small interface but checks at run time whether the value can do something extra, and uses it if so. io.Copy checks whether the source has WriteTo; a streaming handler checks whether the response writer has Flush.
Common misunderstanding: "If my writer is wrapped, the wrapper has all the original's methods." Only the methods of the embedded interface type are promoted. A logging middleware that embeds http.ResponseWriter exposes Header, Write and WriteHeader — and silently drops Flush, Hijack and ReadFrom.
Definition: the pattern is a type assertion to an interface: if wt, ok := src.(io.WriterTo); ok { return wt.WriteTo(dst) }. io.WriterTo's documentation: "The Copy function uses WriterTo if available." net/http documents Flusher ("Flush sends any buffered data to the client") and says of Hijacker that "Handlers should always test for this ability at runtime." Since Go 1.20, http.NewResponseController(w) calls Flush, FlushError, Hijack, SetReadDeadline, SetWriteDeadline and EnableFullDuplex if available; "The ResponseWriter should be the original value passed to the Handler.ServeHTTP method, or have an Unwrap method returning the original ResponseWriter", and it returns an error matching http.ErrNotSupported ("feature not supported") otherwise.
1 handler -> w.(http.Flusher) w is *statusRecorder (embeds ResponseWriter)
2 -> ok == false Flush hidden: SSE events buffer until the handler returns
3 handler -> http.NewResponseController(w).Flush()
4 -> statusRecorder has no Flush, but has Unwrap()
5 -> follows Unwrap to *http.response, calls Flush -> events stream
6 plain writer with no Flush and no Unwrap -> error "feature not supported"Real scenario: Server-Sent Events stop streaming after someone adds a metrics middleware; a WebSocket upgrade fails behind a wrapper that hides Hijack; io.Copy from a *os.File to a TCP connection uses sendfile through ReadFrom — until a counting wrapper hides it and throughput drops. database/sql/driver uses the same pattern for driver.QueryerContext, driver.Pinger and friends.
| Optional interface | Checked by | What you lose if hidden |
|---|---|---|
io.WriterTo / io.ReaderFrom | io.Copy, io.CopyN, bufio | Zero-copy paths (sendfile, splice), extra allocation |
http.Flusher | Streaming handlers, SSE | Incremental delivery |
http.Hijacker | WebSocket libraries | Upgrade fails |
io.StringWriter | io.WriteString | A []byte conversion per call |
fmt.Formatter, fmt.GoStringer | fmt | Custom verbs, %#v |
json.Marshaler, encoding.TextMarshaler | encoding/json | Custom encoding |
driver.*Context interfaces | database/sql | Context cancellation in old drivers |
Fix / how to use it: in wrappers, add Unwrap() http.ResponseWriter and use http.ResponseController in handlers; forward optional methods you know matter; check and fall back gracefully. Middleware wrappers are built in Middlewares.
// Package optional shows the optional-interface (upgrade) pattern and the
// wrapper problem it causes.
package optional
import (
"fmt"
"io"
"net/http"
"time"
)
// CopyStats reports whether io.Copy could take a fast path. io.Copy itself
// checks src.(io.WriterTo) and then dst.(io.ReaderFrom) before falling back
// to a buffer loop.
func CopyStats(dst io.Writer, src io.Reader) string {
_, wt := src.(io.WriterTo)
_, rf := dst.(io.ReaderFrom)
return fmt.Sprintf("src WriterTo=%t dst ReaderFrom=%t", wt, rf)
}
// statusRecorder is a typical logging-middleware wrapper. Embedding the
// interface http.ResponseWriter promotes only Header, Write, WriteHeader:
// Flush, Hijack and ReadFrom of the real writer are hidden.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
// Unwrap lets http.ResponseController reach the original writer (Go 1.20+).
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
// Logging wraps a handler with statusRecorder.
func Logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
next.ServeHTTP(&statusRecorder{ResponseWriter: w, status: http.StatusOK}, req)
})
}
// StreamOld uses the pre-1.20 upgrade: assert to http.Flusher. Behind a
// wrapper without Flush, the assertion fails and nothing is flushed early.
func StreamOld(w http.ResponseWriter, _ *http.Request) {
f, ok := w.(http.Flusher)
fmt.Fprintf(w, "flusher=%t\n", ok)
if ok {
f.Flush()
}
}
// StreamNew uses http.ResponseController, which follows Unwrap and returns
// an error wrapping http.ErrNotSupported instead of silently doing nothing.
func StreamNew(w http.ResponseWriter, _ *http.Request) {
rc := http.NewResponseController(w)
for i := range 3 {
fmt.Fprintf(w, "tick %d\n", i)
if err := rc.Flush(); err != nil {
fmt.Fprintf(w, "flush error: %v\n", err)
return
}
time.Sleep(time.Millisecond)
}
}Comparable interfaces and map keys Important
In plain words: you can compare interface values with == and use them as map keys. Two are equal when they hold the same type and equal values. If both hold the same type and that type cannot be compared (a slice, map or func), the program panics.
Common misunderstanding: "If it compiles, == is safe." Interface comparison is checked at run time. map[any]int compiles, and the first slice key crashes the process.
Definition: the spec: "Two interface values are equal if they have identical dynamic types and equal dynamic values or if both have value nil." "A comparison of two interface values with identical dynamic types causes a run-time panic if that type is not comparable. This behavior applies not only to direct interface value comparisons but also when comparing arrays of interface values or structs with interface-valued fields." A type is strictly comparable "if it is comparable and not an interface type nor composed of interface types". Since Go 1.20, any satisfies the comparable constraint, so Index[any, V] compiles and may panic.
1 any(1) == any(1) -> true
2 any(1) == any(int64(1)) -> false (different dynamic types)
3 any([]int{1}) == any(map[string]int{}) -> false, no panic (types differ)
4 any([]int{1}) == any([]int{1}) -> panic: runtime error: comparing uncomparable type []int
5 m := map[any]int{}; m[[]string{"x"}]++ -> panic: runtime error: hash of unhashable type []string
6 var p *int; any(nil) == any(p) -> falseReal scenario: a dedup cache keyed by any receives a []string tag list from a new caller; an errors.Is call against a target whose dynamic type is an uncomparable struct (errors.Is guards this: it computes reflectlite.TypeOf(target).Comparable() before using ==); a generic Set[T comparable] instantiated with any.
| Key type | Compile-time safe | Run-time panic possible |
|---|---|---|
string, int64, struct of those | Yes | No |
any, error, fmt.Stringer | Compiles | Yes, if the dynamic type is uncomparable |
[]byte, map, func | Does not compile as a key | — |
| Struct containing an interface field | Compiles | Yes |
Array of any | Compiles | Yes |
Fix / how to use it: use strictly comparable key types (string, a small struct); convert slices to strings (strings.Join, a hash) before keying; constrain generics with comparable and do not instantiate them with interface types on untrusted input.
// Package comparable shows interface equality and interfaces as map keys.
package comparable
import "fmt"
// Equal compares two interface values: same dynamic type and equal values.
// It panics if both hold the same uncomparable type (slice, map, func).
func Equal(a, b any) bool { return a == b }
// SafeEqual recovers the panic and reports it.
func SafeEqual(a, b any) (eq bool, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
return a == b, nil
}
// Count uses map[any]int; inserting an uncomparable dynamic type panics.
func Count(keys ...any) (m map[any]int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
m = map[any]int{}
for _, k := range keys {
m[k]++
}
return m, nil
}
// Key is a strictly comparable key type: prefer it over any.
type Key struct {
Tenant string
ID int64
}
// Index is generic over comparable keys; the compiler rejects slices,
// but since Go 1.20 an interface type argument such as any is accepted
// and the runtime panic comes back.
func Index[K comparable, V any](items []V, key func(V) K) map[K]V {
m := make(map[K]V, len(items))
for _, it := range items {
m[key(it)] = it
}
return m
}Interface pollution and mocks Important
In plain words: interface pollution is declaring interfaces nobody needs: one per struct, before there is a second implementation, "for testability". It adds indirection, hides the real type from readers and the compiler, and makes every change twice as large.
Common misunderstanding: "You need an interface to write a test." You need a seam, and the seam belongs to the consumer. Many types are tested best through their real implementation (httptest.Server, an in-memory store, a temporary directory).
Definition: the review guide: "Do not define interfaces before they are used: without a realistic example of usage, it is too difficult to see whether an interface is even necessary, let alone what methods it ought to contain." Signs of pollution: an exported interface with exactly one implementation in the same package; constructors returning the interface; interfaces mirroring every method of a struct; mocks generated for types you own.
1 week 1: type UserService interface { 14 methods }; type userService struct{}; NewUserService() UserService
2 week 2: add method 15 -> edit interface, struct, generated mock, 6 hand-written fakes
3 week 3: reader jumps to definition -> lands on the interface, not the code
4 refactor: return *UserService; consumers declare the 1–2 methods they use
5 result: method 16 touches one file; fakes are 5 linesReal scenario: a Laravel team porting to Go mirrors every ServiceInterface; a gomock-generated mock with 30 expectations breaks on every refactor; a repository interface with FindByID, FindAll, Save, Delete, Count… where each handler uses one.
| Signal | Pollution? | Action |
|---|---|---|
| One implementation, interface next to it, exported | Usually | Return the struct; let consumers define interfaces |
| Two real implementations (Postgres, in-memory) | No | Keep, but keep it small |
| Interface for an external system (payment gateway, clock, SMTP) | No | Consumer-side, minimal |
| Interface with 10+ methods | Usually | Split by consumer |
| Interface only used by a mock | Yes | Test through the real type or a fake of a small interface |
Fix / how to use it: start concrete; extract an interface at the consumer when a second implementation or a test seam actually appears. Fakes vs mocks vs testify are in Mocking with Interfaces.
Mechanics
Dynamic dispatch, heap escape and devirtualisation Important
A call through an interface loads a function pointer from the itab and calls it indirectly. That is cheap (a few nanoseconds) but it blocks inlining, so the loop around it cannot be optimised as well as a direct call. Converting a non-pointer value to an interface may copy it to the heap. The compiler removes the indirection when it can prove the dynamic type (devirtualisation), and since Go 1.21 profile-guided optimisation can add a guarded direct call for the hottest type at a call site.
Real measurements from the dispatch snippet (Go 1.27.4, Apple M4 Pro, 1024 rectangles, go test -bench . -benchtime 200ms):
| Benchmark | ns/op | B/op | allocs/op | Why |
|---|---|---|---|---|
SumDirect ([]Rect) | 758.5 | 0 | 0 | Rect.Area inlined into the loop |
SumIface ([]Shape) | 3049 | 0 | 0 | Indirect call per element, no inlining |
SumGeneric[Rect] | 2883 | 0 | 0 | GC-shape stenciling: the method call goes through a dictionary |
Box ([]Rect → []Shape) | 7200 | 34816 | 1025 | One heap box per 16-byte Rect plus the slice |
go build -gcflags=-m ./dispatch/ prints the compiler's decisions verbatim:
dispatch/dispatch.go:11:6: can inline Rect.Area
dispatch/dispatch.go:57:15: devirtualizing s.Area to Rect
dispatch/dispatch.go:57:15: inlining call to Rect.Area
dispatch/dispatch.go:25:15: leaking param content: ss
dispatch/dispatch.go:46:13: make([]Shape, len(rs)) escapes to heap
dispatch/dispatch.go:48:12: r escapes to heap
dispatch/dispatch.go:56:20: Rect{...} does not escapeRead it as: the direct method can be inlined; in Devirtualized() the compiler saw var s Shape = Rect{...} and turned s.Area() into a direct, inlined call, so the Rect did not escape; in Box each r stored in []Shape escapes. The generic version is not faster than the interface one here — exactly the Go blog's warning that "using a type parameter will generally not be faster than using an interface type".
// Package dispatch compares a direct call, an interface call and a generic
// call, and shows what escapes to the heap when a value enters an interface.
package dispatch
// Shape is a one-method interface.
type Shape interface{ Area() float64 }
// Rect is a small value type.
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
// SumDirect calls the concrete method: static call, inlinable.
func SumDirect(rs []Rect) float64 {
var s float64
for _, r := range rs {
s += r.Area()
}
return s
}
// SumIface calls through the itab: an indirect call the compiler
// usually cannot inline (unless it can prove the dynamic type, or PGO
// devirtualizes the hot call site).
func SumIface(ss []Shape) float64 {
var s float64
for _, sh := range ss {
s += sh.Area()
}
return s
}
// SumGeneric is instantiated with a GC shape; method calls on T still go
// through a dictionary, so it is not automatically faster than SumIface.
func SumGeneric[T Shape](ss []T) float64 {
var s float64
for _, sh := range ss {
s += sh.Area()
}
return s
}
// Box converts each Rect to Shape. A Rect is two float64s (16 bytes), too
// big for the interface data word, so each conversion may allocate.
func Box(rs []Rect) []Shape {
out := make([]Shape, len(rs))
for i, r := range rs {
out[i] = r
}
return out
}
// Devirtualized: the compiler sees the concrete type at the call site
// and can turn the interface call into a direct one.
func Devirtualized() float64 {
var s Shape = Rect{W: 2, H: 3}
return s.Area()
}| Knob / tool | What it shows or changes |
|---|---|
go build -gcflags=-m (-m -m for reasons) | Inlining, devirtualisation, escape decisions |
go test -bench . -benchmem | ns/op, B/op, allocs/op |
testing.AllocsPerRun | Allocation count in a unit test (used in TestBoxAllocates) |
default.pgo in the main package, go build -pgo=auto | PGO: inlining and devirtualisation of hot interface calls (Go 1.21+) |
go tool pprof | Which interface call sites are hot enough to matter |
Type switch and assertion cost Good to know
An assertion to a concrete type compares the type word with one pointer: essentially free. An assertion to an interface type needs the itab for (target interface, dynamic type): the runtime looks it up in a global hash table and caches it; the first lookup for a pair builds it by walking both method lists ("O(ni + nt)" per Cox, by sorting both tables). Type switches use the Hash copied into the itab/type to jump quickly to candidate cases. In practice: concrete cases are cheaper than interface cases; neither is a reason to avoid type switches at a boundary.
Error texts decoded Must-know
| Text | Produced by | Meaning |
|---|---|---|
interface conversion: interface {} is int, not string | runtime.TypeAssertionError | Concrete assertion failed; static type was any |
interface conversion: io.Reader is *os.File, not *bytes.Buffer | same | Concrete assertion on a non-empty interface |
interface conversion: interface {} is nil, not string | same | The interface was nil |
interface conversion: X is not Y: missing method M | same | Interface assertion; dynamic type lacks a method |
... (types from different packages) | same | Two types print the same (e.g. two config.Config from different modules) |
runtime error: comparing uncomparable type []int | runtime, == | Same uncomparable dynamic type |
runtime error: hash of unhashable type []string | runtime, map access | Uncomparable map key |
X does not implement Y (method M has pointer receiver) | compiler | Use &x or a value receiver |
X does not implement Y (missing method M) | compiler | Method missing or misspelled |
X does not implement Y (wrong type for method M) | compiler | Signature differs; the compiler prints have/want |
impossible type assertion: r.(string) | compiler | The concrete type cannot be stored in that interface |
second argument to errors.As must be a non-nil pointer to either a type that implements error, or to any interface type | go vet (errorsas) | Wrong errors.As target |
feature not supported | http.ErrNotSupported | ResponseController could not find the method |
Go
Before
The classic bug, compiled and tested in the nilerror package: a helper returns the concrete pointer type, and the interface conversion makes every success look like a failure.
package nilerror
import (
"errors"
"testing"
)
func TestBuggyIsNeverNil(t *testing.T) {
err := ValidateBuggy("a@example.com")
if err == nil {
t.Fatal("expected the classic bug: non-nil error holding a nil pointer")
}
if got := Describe(err); got != "err==nil:false type:*nilerror.ValidationError value:<nil>" {
t.Fatalf("got %q", got)
}
if err := ValidateWrapped("a@example.com"); err == nil {
t.Fatal("wrapped helper has the same bug")
}
}
func TestFixed(t *testing.T) {
if err := Validate("a@example.com"); err != nil {
t.Fatalf("want nil, got %v", err)
}
err := Validate("")
var verr *ValidationError
if !errors.As(err, &verr) || verr.Field != "email" {
t.Fatalf("errors.As failed on %v", err)
}
if got := Describe(nil); got != "err==nil:true type:<nil> value:<nil>" {
t.Fatalf("got %q", got)
}
}After
A consumer-defined interface, a concrete return type and fakes written in a few lines; the real *Store satisfies the same interface without knowing it exists.
package consumer
import (
"context"
"errors"
"testing"
)
// fakeLookup is a hand-written fake for the consumer's own interface.
type fakeLookup map[int64]string
func (f fakeLookup) Email(_ context.Context, id int64) (string, error) {
if e, ok := f[id]; ok {
return e, nil
}
return "", ErrNotFound
}
func TestWelcomeWithFakes(t *testing.T) {
var sent []string
n := NewNotifier(fakeLookup{1: "a@example.com"}, SenderFunc(func(_ context.Context, to, _ string) error {
sent = append(sent, to)
return nil
}))
if err := n.Welcome(context.Background(), 1); err != nil {
t.Fatal(err)
}
if len(sent) != 1 || sent[0] != "a@example.com" {
t.Fatalf("sent = %v", sent)
}
if err := n.Welcome(context.Background(), 2); !errors.Is(err, ErrNotFound) {
t.Fatalf("want ErrNotFound, got %v", err)
}
}
func TestWelcomeWithRealStore(t *testing.T) {
s := NewStore()
ctx := context.Background()
_ = s.Put(ctx, 7, "b@example.com")
var got string
n := NewNotifier(s, SenderFunc(func(_ context.Context, to, _ string) error { got = to; return nil }))
if err := n.Welcome(ctx, 7); err != nil || got != "b@example.com" {
t.Fatalf("got %q %v", got, err)
}
}The Go angle
The standard library is the best style guide for interfaces: io (Reader, Writer, Closer, Seeker, WriterTo, ReaderFrom and their compositions), fmt.Stringer and fmt.Formatter, error, sort.Interface, http.Handler with the HandlerFunc adapter, http.ResponseWriter with optional Flusher/Hijacker and ResponseController, database/sql/driver with a dozen optional interfaces, encoding.TextMarshaler/json.Marshaler, hash.Hash, context.Context (an interface with four methods so that every implementation can be wrapped), and slog.Handler / slog.LogValuer. Tooling: go vet checks errors.As targets and Printf verbs against Stringer/error; gopls "implementations" and "Go to implementation" find which types satisfy an interface (the answer you lose with implicit satisfaction); staticcheck flags impossible assertions and some nil-interface comparisons; golangci-lint linters ireturn (interfaces returned) and interfacebloat (too many methods) police the style rules on this page.
Solving the classic problems
| Problem | Solution | Advantage | Cost / limitation |
|---|---|---|---|
| Non-nil error holding nil pointer | Return error, return literal nil | Correct err != nil everywhere | Discipline; linters only catch some shapes |
| Panic on wrong assertion | Comma-ok or type switch with default | No crash on unexpected input | You must handle the "else" branch |
| Matching wrapped errors | errors.As (or errors.AsType, Go 1.26+) | Walks Unwrap chains and errors.Join trees | Target must be a pointer |
| Mocking a dependency | Consumer-defined small interface + fake | Tiny fakes, no generator | One interface per consumer (by design) |
Wrapper hides Flush/Hijack | Unwrap() + http.ResponseController | Works through any depth of middleware | Go 1.20+ |
Losing io.Copy fast paths | Forward ReadFrom/WriteTo or do not wrap | Keeps sendfile/splice | More methods on wrappers |
| JSON numbers lose precision | Typed structs, or UseNumber | Exact 64-bit integers | json.Number needs parsing |
| Panicking map keys | Strictly comparable key types | Compile-time safety | Convert slices to strings/hashes |
| Sorting with three methods | slices.SortFunc with cmp.Compare/cmp.Or | No named type; multi-key sorts read clearly | Go 1.21+; sort.Stable → slices.SortStableFunc |
| Interface on a hot path | Concrete type, generics, or PGO | Inlining | Less flexibility |
errors.As with interfaces
errors.As "finds the first error in err's tree that matches target"; a target can be a pointer to a concrete type (*net.DNSError) or to an interface type, and then "An error matches target if the error's concrete value is assignable to the value pointed to by target". Matching by behaviour (an interface with Retry() or Timeout()) lets the caller react to any error that can tell it how, without importing the package that defined it. As "panics if target is not a non-nil pointer to either a type that implements error, or to any interface type"; go vet catches the static cases. Since Go 1.26, errors.AsType[T](err) returns the match directly; the snippet keeps errors.As because the module targets Go 1.24.
// Package errorsas matches errors by behaviour (an interface) and by type.
package errorsas
import (
"errors"
"fmt"
"net"
"time"
)
// RateLimited is a concrete error type with a behaviour method.
type RateLimited struct{ RetryAfter time.Duration }
func (e *RateLimited) Error() string {
return fmt.Sprintf("rate limited, retry after %s", e.RetryAfter)
}
func (e *RateLimited) Temporary() bool { return true }
func (e *RateLimited) Retry() time.Duration { return e.RetryAfter }
// retryable is a behaviour, declared by the consumer that cares about it.
type retryable interface {
error
Retry() time.Duration
}
// timeout matches net.Error, context.DeadlineExceeded's type and others.
type timeout interface{ Timeout() bool }
// Classify walks the wrapped chain with errors.As. The target may be a
// pointer to an interface type: As then matches any error in the chain
// whose dynamic type implements it.
func Classify(err error) string {
var r retryable
if errors.As(err, &r) {
return "retry in " + r.Retry().String()
}
var t timeout
if errors.As(err, &t) && t.Timeout() {
return "timeout"
}
var dnsErr *net.DNSError // pointer to a concrete type
if errors.As(err, &dnsErr) {
return "dns: " + dnsErr.Name
}
return "fatal"
}
// CallAPI wraps a cause the way a client library would.
func CallAPI(cause error) error { return fmt.Errorf("call billing: %w", cause) }sort.Interface vs slices.SortFunc
Effective Go's example of a type implementing two interfaces is sort.Interface ("Len(), Less(i, j int) bool, and Swap(i, j int)"). Since Go 1.21 the generic slices.SortFunc(s, cmp) takes a comparison function returning negative/zero/positive and needs no named type. On this machine sorting 10 000 orders by total took 536 723 ns/op with sort.Sort and 473 239 ns/op with slices.SortFunc (one run, -benchtime 300ms): the generic version avoids the interface calls for Less and Swap. sort.Sort and slices.SortFunc are not stable; use sort.Stable or slices.SortStableFunc when equal keys must keep their order, or make the comparison total with cmp.Or.
// Package sorting contrasts sort.Interface with slices.SortFunc.
package sorting
import (
"cmp"
"slices"
"sort"
"strings"
)
// Order is a row from an orders table.
type Order struct {
ID int64
Customer string
TotalCts int64
}
// byTotal implements sort.Interface: three methods, called through an
// interface for every comparison and swap.
type byTotal []Order
func (s byTotal) Len() int { return len(s) }
func (s byTotal) Less(i, j int) bool { return s[i].TotalCts < s[j].TotalCts }
func (s byTotal) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// SortOld is the pre-generics style (still valid; sort.Sort is not stable).
func SortOld(os []Order) { sort.Sort(byTotal(os)) }
// SortStableOld keeps equal totals in input order.
func SortStableOld(os []Order) { sort.Stable(byTotal(os)) }
// SortNew is the Go 1.21+ style: a comparison function, no named type.
// Ties on total are broken by customer, then by ID, so the order is total.
func SortNew(os []Order) {
slices.SortFunc(os, func(a, b Order) int {
return cmp.Or(
cmp.Compare(a.TotalCts, b.TotalCts),
strings.Compare(a.Customer, b.Customer),
cmp.Compare(a.ID, b.ID),
)
})
}
// SortByTotal is the like-for-like counterpart of SortOld for benchmarks.
func SortByTotal(os []Order) {
slices.SortFunc(os, func(a, b Order) int { return cmp.Compare(a.TotalCts, b.TotalCts) })
}
// IDs extracts IDs for assertions.
func IDs(os []Order) []int64 {
out := make([]int64, len(os))
for i, o := range os {
out[i] = o.ID
}
return out
}Generics vs interfaces
The Go blog When To Use Generics gives the rule: "If all you need to do with a value of some type is call a method on that value, use an interface type, not a type parameter." And: "if the implementation is different for each type, then use an interface type and write different method implementations, don't use a type parameter." Use type parameters when the code is identical for every type (containers, slices, maps, a generic Cache[K, V]), when you need to return the same type you received, or to remove an any + assertion pair. The full story is in Generics.
| Need | Interface | Type parameter |
|---|---|---|
| Call methods whose implementation differs per type | Yes | No |
| Same algorithm over many element types | No (needs any + assertions) | Yes |
Heterogeneous collection ([]Shape of rects and circles) | Yes | No (one T per instantiation) |
| Return the caller's concrete type | No (returns the interface) | Yes |
Union of types (~int | ~float64) | Only as a constraint | Yes |
| Avoid boxing each element | No | Yes |
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One implementation, no test seam needed | Concrete type | — | Simplest; the compiler sees everything |
| A dependency on an external system (DB, SMTP, payments, clock) | Small consumer-defined interface | Func adapter, fake in tests | Swap real/fake; isolate failures |
| Several real implementations with different behaviour | Interface | var _ I = (*T)(nil) per implementation | Dynamic dispatch is the point |
| Same algorithm for many element types | Generics | cmp.Ordered, comparable | No boxing, no assertions |
| Unknown JSON shape at the edge | map[string]any + type switch | Convert to structs early; UseNumber | Typed core, untyped edge |
| Logging / formatting values | any | fmt.Stringer, slog.LogValuer | Designed for it |
| Optional extra ability | Optional interface via comma-ok | Unwrap, ResponseController | Backwards-compatible upgrades |
| Classifying errors | errors.As with a behaviour interface | errors.Is for sentinels | Works through wrapping |
| Closed set of variants you own | Interface with a method per behaviour | Unexported marker method to seal it | Adding a variant cannot miss a case |
| Hot loop over millions of values | Concrete type or generics | PGO, -gcflags=-m | Inlining matters there |
| Map key of mixed types | A struct key | — | Avoid map[any] panics |
In architecture: from a single process to a distributed system
Interfaces are a compile-time contract inside one Go binary. They stop at the process boundary: across the network the contract is a schema (JSON, Protobuf, OpenAPI), and Go interfaces only describe the client and server code at each end.
Monolith: one process, one database
In a single binary, interfaces mark the seams to the outside world: *sql.DB stays concrete inside the repository; the service package declares type orderStore interface{ Get(ctx, id) (Order, error) }; handlers take http.Handler/io.Writer; the clock is func() time.Time. Simplest correct use: concrete types everywhere, interfaces only where tests need a fake or a second implementation exists. Repository wiring with database/sql and pgx is in database/sql & pgx.
Modular monolith and multiple databases
Module boundaries are where consumer-defined interfaces pay off most: the billing module declares the two methods it needs from customers and never imports customers' internals; main wires the concrete *customers.Service into it. This keeps the dependency graph acyclic and lets a module later become a service by swapping the implementation for an HTTP or gRPC client that satisfies the same small interface. A shared "contracts" package with every interface recreates the coupling the modules were meant to avoid (Modular Monolith).
Microservices
Across services there is no itab: what travels is bytes. The consumer-defined interface becomes the seam between business code and a client adapter:
1 orders service: type paymentAPI interface{ Charge(ctx, req) (ChargeID, error) }
2 adapter: *paymentsgrpc.Client implements paymentAPI by calling Payments.Charge over gRPC
3 network: protobuf ChargeRequest -> payments service
4 payments: gRPC server struct implements the generated PaymentsServer interface
5 error path: gRPC status code -> adapter maps to *RateLimited / ErrDeclined -> orders uses errors.AsErrors lose their Go type at the boundary: the server's *RateLimited becomes a status code and details; the client must rebuild a typed error so callers can still errors.As on behaviour. Generated gRPC code is the one place where a producer-side interface (PaymentsServer) is normal: it is a contract generated from the schema, with an Unimplemented...Server struct embedded for forward compatibility (gRPC & Protobuf in Go). Event payloads decoded into any need the same discipline as JSON: decode into versioned structs (Message Design & Schema Evolution).
Distributed data: replicas, caches, queues
A read-through cache is a decorator that satisfies the same small interface as the store (Get(ctx, id)), so handlers do not know whether data comes from Redis, a replica or the primary; a readerStore/writerStore pair of interfaces makes the read-replica routing explicit in types. The JSON float64 trap reappears when IDs travel through caches or message brokers as untyped JSON — use strings or UseNumber. Retries and timeouts are classified by behaviour interfaces (Timeout() bool, Retry() time.Duration) instead of by concrete driver types (Timeouts, Retries & Jitter).
Scaling path: 1×, 10×, 100×
| Load | What changes for interfaces |
|---|---|
| 1× | Concrete types; a few consumer interfaces for tests; no performance concern |
| 10× | Profile: interface calls in hot loops and []any boxing show up; move hot paths to concrete or generic code; add wrappers carefully (keep ReadFrom/Flush) |
| 100× | PGO-built binaries devirtualise hot call sites; allocation budgets per request (-benchmem, AllocsPerRun); avoid any in logging hot paths (slog.Attr constructors) |
Lab
All commands run on the host from docs/snippets/go/interfaces-type-switches/go with the Go 1.27.4 toolchain; the outputs below were captured, not invented. Nothing needs a database or network.
Run every test.
bashgo vet ./... && go test ./... # ok academy/interfaces-type-switches/assertswitch # ok academy/interfaces-type-switches/comparable # ok academy/interfaces-type-switches/consumer # ok academy/interfaces-type-switches/dispatch # ok academy/interfaces-type-switches/embedding # ok academy/interfaces-type-switches/errorsas # ok academy/interfaces-type-switches/jsonany # ok academy/interfaces-type-switches/methodset # ok academy/interfaces-type-switches/nilerror # ok academy/interfaces-type-switches/optional # ok academy/interfaces-type-switches/sortingSee the panic text of a failed assertion. Put this in a scratch module and run it:
gopackage main func main() { var v any = 42 _ = v.(string) }textpanic: interface conversion: interface {} is int, not string goroutine 1 [running]: main.main() .../main.go:5 +0x34 exit status 2See the compiler refuse a value with pointer-receiver methods. Add
var _ io.Writer = Counter{},var _ fmt.Stringer = Temp(1),r.(string)and a duplicate case to a scratch file andgo build:text./main.go:16:20: cannot use Counter{} (value of struct type Counter) as io.Writer value in variable declaration: Counter does not implement io.Writer (method Write has pointer receiver) ./main.go:17:23: cannot use Temp(1) (constant 1 of float64 type Temp) as fmt.Stringer value in variable declaration: Temp does not implement fmt.Stringer (missing method String) ./main.go:19:6: impossible type assertion: r.(string) string does not implement io.Reader (missing method Read) ./main.go:22:12: duplicate case int in type switch ./main.go:22:7: previous caseWatch the nil-pointer error bug and the JSON float64 trap in the tests.
bashgo test -v -run 'TestBuggyIsNeverNil|TestDefaultFloat64' ./nilerror/ ./jsonany/ # --- PASS: TestBuggyIsNeverNil (asserts "err==nil:false type:*nilerror.ValidationError value:<nil>") # --- PASS: TestDefaultFloat64 (asserts 9007199254740993 -> 9007199254740992)Watch escape analysis and devirtualisation.
bashgo build -gcflags=-m ./dispatch/ 2>&1 | grep -E 'devirtualizing|escapes' # dispatch/dispatch.go:57:15: devirtualizing s.Area to Rect # dispatch/dispatch.go:46:13: make([]Shape, len(rs)) escapes to heap # dispatch/dispatch.go:48:12: r escapes to heapMeasure dispatch and boxing.
bashgo test -run xxx -bench . -benchtime 200ms ./dispatch/ ./sorting/ # BenchmarkDirect-12 297715 758.5 ns/op # BenchmarkIface-12 79180 3049 ns/op # BenchmarkGeneric-12 85797 2883 ns/op # BenchmarkBox-12 33211 7200 ns/op 34816 B/op 1025 allocs/op # BenchmarkSortInterface-12 655 536723 ns/op # BenchmarkSortFunc-12 765 473239 ns/opNumbers vary by machine; the ratios (direct ≈ 4× faster than interface here, boxing one allocation per element) are the lesson.
Common misconceptions
| Belief | Reality |
|---|---|
| An interface holding a nil pointer is nil | It is non-nil: the type word is set |
| Types must declare which interfaces they implement | Satisfaction is implicit; var _ I = (*T)(nil) is an optional compile-time check |
If v.Method() compiles, v satisfies the interface | Not for pointer-receiver methods on values: only *T does |
| A type assertion converts types | It only checks; any(int32(5)).(int) fails |
case A, B: gives a variable of A or B | It keeps the switched expression's type |
| Type switch cases are matched by specificity | In source order; put concrete types before interfaces |
any is Go's flexible parameter type | It moves checks to run time; use small interfaces or generics |
| JSON numbers decode to int | Inside any they are float64; large IDs lose digits |
| A wrapper keeps all methods of what it wraps | Embedding an interface promotes only that interface's methods |
Comparing interfaces with == is always safe | Panics when both hold the same uncomparable type |
| Every struct needs an interface for testing | Consumer-defined seams only where needed; test real types otherwise |
| Generics are faster than interfaces | Often not; GC-shape stenciling calls methods through dictionaries |
| Pointers to interfaces are needed to modify them | *io.Reader has no methods; pass the interface value |
Cheat sheet
| Topic | Remember |
|---|---|
| Satisfaction | Method set must contain all methods; no implements keyword |
| Pointer receivers | Only *T satisfies; pass &v |
| Compile-time check | var _ io.Writer = (*T)(nil) |
| Interface size | One or two methods; "the bigger the interface, the weaker the abstraction" |
| Where to declare | In the consumer package; return concrete structs |
| Representation | iface{tab, data}, eface{_type, data}; itab cached per pair |
| Nil | Nil only if type and value are unset; return literal nil |
| Assertion | v, ok := x.(T); single form panics interface conversion: ... |
| Type switch | case nil first; concrete before interface; one type per case to get a typed variable |
any | Alias of interface{} (1.18); JSON numbers become float64; UseNumber |
| Embedding | Interfaces compose (io.ReadWriteCloser); struct-embedded interfaces hide extras |
| Optional interfaces | io.WriterTo, http.Flusher; wrappers need Unwrap; use ResponseController |
| Comparability | Same uncomparable dynamic type panics; avoid map[any] |
| Errors | errors.As(err, &iface) matches behaviour through wrapping |
| Performance | Interface calls block inlining; boxing allocates; -gcflags=-m, PGO |
| Sorting | slices.SortFunc + cmp.Compare/cmp.Or over sort.Interface |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — func (b *Buffer) Write(p []byte) (int, error) is the only method of Buffer. Does var w io.Writer = Buffer{} compile? Must-know
Answer
Answer: No: Buffer does not implement io.Writer (method Write has pointer receiver). The method set of Buffer is empty; only *Buffer has Write. Use &Buffer{}. See Method sets.
2 — A function declared func check() error does var e *AppErr; return e. What does check() != nil give, and why? Must-know
Answer
Answer: true. The returned interface holds (type=*AppErr, value=nil); an interface is nil only if both are unset. Return the literal nil. See Nil interface vs nil pointer.
3 — What exactly does var v any = 42; s := v.(string) print when it fails, and how do you avoid the panic? Must-know
Answer
Answer: panic: interface conversion: interface {} is int, not string. Use s, ok := v.(string); s is "" when ok is false. See Type assertions.
4 — In switch x := v.(type) { case int, int64: return x + 1 }, why does this not compile? Important
Answer
Answer: With two types in one case, x has the type of v (any), and any + 1 is not defined. Split the cases. See Type switches.
5 — A webhook sends {"id": 9007199254740993} and you decode into map[string]any. What is in m["id"]? Must-know
Answer
Answer: A float64 equal to 9007199254740992: JSON numbers in any are float64 and lose precision above 2^53. Decode into a struct with int64, or use Decoder.UseNumber. See any.
6 — After adding a logging middleware, Server-Sent Events arrive only when the request ends. Why, and what is the modern fix? Important
Answer
Answer: The wrapper embeds http.ResponseWriter, which promotes only Header, Write, WriteHeader; w.(http.Flusher) now fails. Add Unwrap() http.ResponseWriter to the wrapper and call http.NewResponseController(w).Flush(). See Optional interfaces.
7 — When can a == b panic for a, b any? Important
Answer
Answer: When both hold the same dynamic type and that type is not comparable (slice, map, func, or a struct/array containing one): runtime error: comparing uncomparable type []int. Different dynamic types just give false. See Comparable interfaces.
8 — Where should type userLookup interface{ Email(ctx context.Context, id int64) (string, error) } live: in the users package or the notify package? Important
Answer
Answer: In notify, the consumer. users returns a concrete *Service; notify lists only the method it needs, so users can grow without breaking anyone, and the fake is tiny. See Accept interfaces, return structs.
9 — Why is SumIface about four times slower than SumDirect in the benchmark, and what can remove the difference without changing the API? Good to know
Answer
Answer: The interface call is indirect and prevents inlining Area into the loop. Devirtualisation (when the compiler proves the type) or PGO (Go 1.21+, which adds a guarded direct call for the hot type) can recover it. See Mechanics.
10 — You want to retry any error that "knows" its retry delay, whichever package defined it. How? Important
Answer
Answer: Declare type retryable interface{ error; Retry() time.Duration } and use var r retryable; if errors.As(err, &r) { ... }. errors.As with an interface target matches any error in the chain whose type implements it. See errors.As.
11 — When is a type parameter the better choice than an interface? Important
Answer
Answer: When the code is the same for every type (containers, sort, map/filter), when you must return the caller's own type, or to remove any + assertions. If you only call methods whose implementation differs per type, use an interface. See Generics vs interfaces.
For PHP/Laravel developers
PHP interfaces are nominal: a class must say so. The PHP manual: "To implement an interface, the implements operator is used." Go has no such operator; any type with the methods qualifies, which is why Go code does not need one interface per class or a container binding UserRepositoryInterface::class to an implementation.
<?php
interface Notifier { public function send(string $to, string $body): void; }
final class SmtpNotifier implements Notifier { // explicit, checked at class load
public function send(string $to, string $body): void { /* ... */ }
}
function welcome(Notifier $n, string $to): void { $n->send($to, 'welcome'); }
// union types and mixed are the closest thing to Go's any + type switch
function render(int|float|string|null $v): string {
return match (true) {
$v === null => 'null',
is_string($v) => "\"$v\"",
default => (string) $v,
};
}| PHP / Laravel | Go |
|---|---|
class X implements I | Nothing to write; var _ I = (*X)(nil) if you want a check |
instanceof I | _, ok := v.(I) |
Union type int|string (PHP 8.0) | No union value types; any + type switch, or a generic constraint ~int | ~string |
mixed | any |
null vs object | nil interface vs interface holding a nil pointer (two different "nothings") |
| Service container binding interfaces to classes | Constructor injection in main; consumer-defined interfaces |
Stringable / __toString() | fmt.Stringer |
Countable, IteratorAggregate | Len() methods, iter.Seq |
Glossary
| Term | Meaning |
|---|---|
| Interface | A type that defines a type set, usually by listing methods |
| Basic interface | An interface defined only by methods; usable as a variable type |
| Type set | The set of types that implement an interface (Go 1.18 spec model) |
| Method set | The methods callable on a type; *T includes T's methods, not the reverse |
| Implicit satisfaction | A type implements an interface by having its methods, without a declaration |
| Structural typing | Compatibility by shape (methods), not by declared name |
| Duck typing | "If it has Read, it's a reader"; Go does it statically |
| Small interface | One or two methods, named after the method (io.Reader) |
io.Reader / io.Writer | The byte-stream interfaces with Read / Write |
fmt.Stringer | Interface with String() string, used by fmt |
error | Predeclared interface with Error() string |
| Accept interfaces, return structs | Take minimal interfaces as parameters, return concrete types |
| Consumer-defined interface | Interface declared in the package that calls the methods |
| Interface value | Two-word pair of type information and data |
| itab | Runtime table for an (interface, concrete type) pair: types, hash, method pointers |
| iface / eface | Runtime layouts of non-empty and empty interfaces |
| Static type | The declared type of a variable (io.Reader) |
| Dynamic type | The concrete type stored in an interface value at run time |
| Dynamic value | The concrete value stored in an interface value |
| Nil interface | An interface with neither type nor value; == nil is true |
| Interface holding a nil pointer | Type set, value a nil pointer; == nil is false |
| Type assertion | x.(T): check and extract the dynamic value as T |
| Comma-ok | The two-result form v, ok := x.(T) that does not panic |
| Interface conversion panic | interface conversion: ... from a failed single-result assertion |
| Type switch | switch x := v.(type): branch on the dynamic type |
case nil | Type-switch case for a nil interface value |
any | Alias for interface{} since Go 1.18 |
interface{} / empty interface | Interface with no methods; every type implements it |
map[string]any | What encoding/json produces for objects decoded into any |
| float64 numbers | JSON numbers decoded into any; json.Number with UseNumber |
| Interface embedding | Listing interfaces inside an interface to union their methods |
io.ReadWriteCloser | Composition of Reader, Writer and Closer |
| Optional interface | An extra interface checked at run time to use a better path |
http.Flusher | Optional interface of response writers that can flush early |
http.ResponseController | Go 1.20 helper that finds optional methods through Unwrap |
io.WriterTo / io.ReaderFrom | Optional interfaces io.Copy uses for fast paths |
| Interface pollution | Interfaces declared without a need: one per struct, producer-side, "for mocks" |
| Mock / fake | Test implementation of an interface; fakes have behaviour, mocks check calls |
| Comparable | A type whose values can be compared with ==; comparable constraint |
| Uncomparable dynamic type | Slice, map, func (or containing them) inside an interface: == panics |
| Strictly comparable | Comparable and not an interface nor containing interfaces |
| Pointer receiver | A method declared on *T; only *T has it in its method set |
| Dynamic dispatch | Calling a method through the itab's function pointer |
| Devirtualisation | Compiler (or PGO) replacing an interface call with a direct call |
| Escape to heap | A value moved to the heap because it outlives the frame (e.g. boxed in an interface) |
| PGO | Profile-guided optimisation; Go 1.21+ can devirtualise hot interface calls |
| Generics vs interfaces | Same code for many types → type parameters; different behaviour → interfaces |
errors.As | Finds the first error in a tree assignable to the target (concrete or interface) |
errors.AsType | Go 1.26 generic form of errors.As |
sort.Interface | Len, Less, Swap; the pre-generics sorting contract |
slices.SortFunc | Go 1.21 generic sort with a comparison function |
implements | PHP/Java keyword for explicit interface declaration; Go has none |
| Union type | PHP 8 int|string parameter types; in Go, unions exist only in constraints |
References
- Go specification (read 2026-11-26, Go 1.27 era): Interface types, Method sets, Type assertions, Type switches, Comparison operators
- Effective Go: Interfaces and other types, Interface checks, Go FAQ: implements declarations, nil error, method sets
- Go Code Review Comments: Interfaces, Go Proverbs, Compiler optimizations wiki
- Go blog: The Laws of Reflection, When To Use Generics, Error handling and Go, Working with Errors in Go 1.13
- Russ Cox, Go Data Structures: Interfaces (2009), read from the Internet Archive copy (the origin refuses automated fetches from this machine)
- Release notes: Go 1.18, Go 1.20, Go 1.21, Go 1.22, Go 1.24, Go 1.25, Go 1.26, Go 1.27, PGO user guide
- Go source: io/io.go, fmt/print.go, errors/wrap.go, net/http/server.go, sort/sort.go, slices/sort.go, encoding/json/decode.go, runtime/iface.go, runtime/runtime2.go, runtime/error.go, internal/abi/iface.go; package docs read with
go doc(Go 1.27.4) forio.Reader,io.WriterTo,fmt.Stringer,errors.As,net/http.ResponseController,encoding/json.Unmarshal,sort.Interface,slices.SortFunc(pkg.go.dev returned 403 to this machine) - PHP manual: Object interfaces, Type system (union types, mixed)