The Analogy: The Socket Defines the Shape
A wall socket knows nothing about kettles. It specifies a shape — three pins, this spacing, this voltage — and anything presenting that shape works. No appliance manufacturer files paperwork declaring "this kettle is socket-compatible"; the kettle either has the pins or it does not, and you find out the moment you try to plug it in. The socket was designed first and the kettle came later, and neither had to know about the other.
A Go interface is the socket. It is a list of method signatures and nothing else, and a type satisfies it by having those methods — no implements keyword, no declaration, no import of the interface's package. Satisfaction is structural, and the compiler checks it at the moment you plug something in: the assignment, the function call, the append into a slice of that interface type. This is why os.File satisfies io.Writer although os and io were written by different people at different times, and why your own type from this afternoon can be handed to a library from 2013.
Which inverts the usual dependency arrow. In most languages the implementation announces the interfaces it supports, so the interface has to exist first and everybody must agree on it. In Go the consumer declares what it needs. A function that only writes bytes declares a one-method socket and takes that, and every writer in the world already fits — which is why the language's most reused abstractions are one method wide, and why the standard advice is that the bigger the interface, the weaker the abstraction.
Under the surface an interface value is two words: what type is plugged in, and the value or pointer itself. Almost everything surprising follows from that pair. A type assertion or type switch works because the type word is right there. Comparison works because both words are compared. And the notorious trap — an interface that holds a nil pointer is not a nil interface, because the type word is set — is simply what those two words say when you look at them honestly. The empty interface, spelled any, is a socket with no pins at all: everything fits and you have learned nothing.
Syntax or Core Structure
Declaring an interface, satisfying it implicitly, asserting the concrete type back out, and plugging a standard-library socket.
package main
import (
"fmt"
"strings"
)
// The socket: two pins, no implementation.
type Shape interface {
Area() float64
Name() string
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
func (r Rect) Name() string { return "rect" }
type Circle struct{ R float64 }
func (c Circle) Area() float64 { return 3.14159 * c.R * c.R }
func (c Circle) Name() string { return "circle" }
// Compile-time proof that the pins line up. Costs nothing at run time.
var _ Shape = Rect{}
var _ Shape = Circle{}
func describe(s Shape) string {
return fmt.Sprintf("%-6s area=%6.2f", s.Name(), s.Area())
}
func main() {
shapes := []Shape{Rect{3, 4}, Circle{2}, Rect{1, 1}}
for _, s := range shapes {
fmt.Println(describe(s))
}
// Type assertion, two-result form: never panics.
if r, ok := shapes[0].(Rect); ok {
fmt.Println("first is a Rect with W =", r.W)
}
if _, ok := shapes[0].(Circle); !ok {
fmt.Println("first is not a Circle")
}
// Type switch: v has the case's concrete type inside each branch.
for _, s := range shapes {
switch v := s.(type) {
case Rect:
fmt.Printf("%T sides %.0f x %.0f\n", v, v.W, v.H)
case Circle:
fmt.Printf("%T radius %.0f\n", v, v.R)
}
}
// A standard-library socket: *strings.Builder has Write, so it is an io.Writer.
var sb strings.Builder
fmt.Fprintf(&sb, "into a %s", "Writer")
fmt.Println(sb.String())
}
Output:
rect area= 12.00
circle area= 12.57
rect area= 1.00
first is a Rect with W = 3
first is not a Circle
main.Rect sides 3 x 4
main.Circle radius 2
main.Rect sides 1 x 1
into a Writer
Neither Rect nor Circle mentions Shape, and Shape mentions neither of them. The two var _ Shape = ... lines are the idiomatic way to make satisfaction a compile-time error at the point of declaration rather than at some distant call site — they declare a variable nobody can name, assign a zero value to it, and are optimised away entirely.
Technical Depth: The Two Words, Assertions, and Interface Design
What an interface value holds
Two words: a pointer to a type descriptor (with the method table for this type-interface pair) and the data word — the value itself if it is pointer-sized, or a pointer to it otherwise. Storing a non-pointer value in an interface therefore may allocate, which is why hot code sometimes puts *T in the interface even when T would satisfy it.
The typed-nil trap
type MyErr struct{}
func (e *MyErr) Error() string { return "boom" }
func broken() error {
var e *MyErr = nil
return e // returns a non-nil error holding a nil *MyErr
}
func fixed() error {
return nil // the only way to return a genuinely nil error
}
broken() != nil is true, because the interface's type word says *MyErr even though its data word is nil. Every caller's if err != nil fires, and the error message might even come out as <nil>. Two rules avoid it: never declare a concrete error variable and return it on the success path, and never give a function a concrete pointer return type that callers will compare against nil.
| Expression | == nil |
|---|---|
var i error | true — both words are zero |
i = (*MyErr)(nil) | false — type word set, data word nil |
i = &MyErr{} | false |
i.(*MyErr) == nil after the second row | true — you asserted the concrete type back out |
Assertions and type switches
| Form | Behaviour |
|---|---|
v := i.(T) | Panics if i does not hold a T. Use only when a failure is a bug. |
v, ok := i.(T) | Never panics. v is the zero T when ok is false. |
v, ok := i.(SomeInterface) | Asks whether the dynamic type also satisfies another interface. This is how io.Copy finds a ReadFrom shortcut. |
switch v := i.(type) | v is the concrete type in a single-type case, and stays the interface type in case A, B: or default. |
case nil: in a type switch | Matches a nil interface, not an interface holding a nil pointer. |
Method sets decide satisfaction
If any method is declared with a pointer receiver, only *T satisfies the interface. The compiler says so explicitly: "T does not implement I (method M has pointer receiver)". This is the previous lesson's asymmetry, and it is the most common reason a type that obviously has the right methods is rejected.
Embedding and composing interfaces
type Reader interface{ Read(p []byte) (int, error) }
type Writer interface{ Write(p []byte) (int, error) }
type ReadWriter interface {
Reader
Writer
}
Since Go 1.14 embedded interfaces may declare overlapping method names as long as the signatures match. A struct can embed an interface too, which makes the struct satisfy it by forwarding — the standard trick for wrapping an implementation and replacing one method while inheriting the rest, and the escape hatch for satisfying a large interface you only partly care about.
The one-method function adapter
type Handler interface{ Serve(msg string) }
type HandlerFunc func(msg string)
func (f HandlerFunc) Serve(msg string) { f(msg) } // a func type with a method
Now any func(string) becomes a Handler by conversion: HandlerFunc(myFunc). This is exactly http.HandlerFunc, and it is the reason Go's HTTP API accepts both objects and bare functions without overloading.
Comparison, and where it panics
i == j compares the type words and then the values, so two interfaces are equal only when the dynamic types match and the values are equal. If the dynamic type is uncomparable — a slice, map or function — the comparison panics at run time with comparing uncomparable type. An any field inside a struct therefore makes == on that struct a run-time risk rather than a compile-time error.
Design rules that actually matter
- Declare the interface where it is consumed, not next to the implementation.
io.Writerlives iniobecauseiois what needs it. - One or two methods. Every method you add shrinks the set of types that can fit and the number of fakes you can write by hand.
- Accept interfaces, return concrete types. Callers of your constructor want all the methods; callers of your function want the minimum.
- Do not add an interface for a single implementation "for testability" until you actually have the second implementation or the test that needs it. Go lets you introduce it later without touching the implementation, which is the whole point.
- Since Go 1.18, if what you wanted was one algorithm over several concrete types with no shared behaviour, generics are usually the better tool. Interfaces are for behaviour; type parameters are for shape.
Cost
A call through an interface is an indirect call, so it cannot be inlined, and boxing a non-pointer value into an interface may allocate. Both are measurable in tight loops and invisible everywhere else. Module 11 shows how to see it rather than guess.
Real World Example: One Renderer, Four Interchangeable Parts
render names two capabilities and knows no concrete types at all. Everything else in the file plugs into it.
package main
import (
"errors"
"fmt"
"io"
"strings"
)
// Declared next to its consumer, one method wide.
type Store interface {
Get(id string) (string, bool)
}
// A defined map type with a method. Interfaces do not require structs.
type mapStore map[string]string
func (m mapStore) Get(id string) (string, bool) {
v, ok := m[id]
return v, ok
}
// A decorator: satisfies Store and holds a Store.
type failingStore struct {
inner Store
fail map[string]bool
}
func (f failingStore) Get(id string) (string, bool) {
if f.fail[id] {
return "", false
}
return f.inner.Get(id)
}
// A writer that refuses past a byte budget. Pointer receiver, so only
// *shortWriter satisfies io.Writer -- hence the assertion below.
type shortWriter struct {
limit int
n int
out *strings.Builder
}
var _ io.Writer = (*shortWriter)(nil)
func (s *shortWriter) Write(p []byte) (int, error) {
if s.n+len(p) > s.limit {
return 0, errors.New("buffer full")
}
s.n += len(p)
return s.out.Write(p)
}
func render(w io.Writer, s Store, ids []string) error {
for _, id := range ids {
name, ok := s.Get(id)
if !ok {
name = "<missing>"
}
if _, err := fmt.Fprintf(w, "%-4s %s\n", id, name); err != nil {
return err
}
}
return nil
}
func main() {
ids := []string{"a1", "b2", "zz", "c3"}
base := mapStore{"a1": "widget", "b2": "gasket", "c3": "flange"}
var sb strings.Builder
fmt.Println("== base ==")
if err := render(&sb, base, ids); err != nil {
fmt.Println("err:", err)
}
fmt.Print(sb.String())
sb.Reset()
fmt.Println("== flaky ==")
flaky := failingStore{inner: base, fail: map[string]bool{"b2": true}}
if err := render(&sb, flaky, ids); err != nil {
fmt.Println("err:", err)
}
fmt.Print(sb.String())
sb.Reset()
fmt.Println("== short ==")
sw := &shortWriter{limit: 20, out: &sb}
err := render(sw, base, ids)
fmt.Print(sb.String())
if err != nil {
fmt.Printf("err=%v after %d bytes\n", err, sw.n)
}
}
Output:
== base ==
a1 widget
b2 gasket
zz <missing>
c3 flange
== flaky ==
a1 widget
b2 <missing>
zz <missing>
c3 flange
== short ==
a1 widget
err=buffer full after 12 bytes
render never mentions a concrete type, and it never needed to be modified. It asks for a Store and an io.Writer, which between them are two method signatures. The three "different programs" in the output are the same six lines of render with different values dropped into those two sockets. That is the whole payoff: the parameter list is the contract, and it is narrow enough that new implementations cost a few lines each.
mapStore shows that satisfaction is about method sets, not about structs. It is a defined type whose underlying type is map[string]string, and because it is defined rather than an alias, we can hang Get on it. There is no wrapper struct, no field, no constructor -- mapStore{...} is a map literal that happens to satisfy Store. The cost is that mapStore is uncomparable, so while s == nil on a Store variable is fine (that only inspects the type word), comparing two Store values that both hold mapStore would panic.
failingStore is the decorator pattern with no framework behind it: it satisfies Store and holds a Store. Because the interface is one method wide, wrapping it is trivial, and render cannot tell the difference -- in the flaky run, b2 simply becomes <missing> alongside the genuinely absent zz. This is how you inject failures in tests, add caching, add logging, or add retries without any implementation knowing it is being wrapped. A five-method interface would make each decorator a chore of four pass-through methods.
shortWriter is the pointer-receiver rule from the previous lesson, enforced at compile time. Write mutates s.n, so it must take *shortWriter; that means shortWriter (the value type) does not satisfy io.Writer, and var _ io.Writer = (*shortWriter)(nil) documents which of the two does. Note the typed nil in that assertion: it is a *shortWriter that happens to be nil, used purely for its type, and it costs nothing at run time. The short run then shows the error path -- the first line is 12 bytes ("a1" padded to 4, a space, "widget", a newline), the second would take it to 24 over a budget of 20, so Write returns an error, fmt.Fprintf passes it up, and render stops at the first failed write instead of silently dropping rows.
Common Mistakes
- Returning a
*MyErrtyped nil as anerror.if err != nilis then true even though there is no error. Declare the return type aserrorand return the literalnil, never a nil concrete pointer. - Writing
implements(or an "implements" comment) and expecting the compiler to check it. Nothing verifies satisfaction until something assigns the type to the interface. Usevar _ Store = mapStore(nil)if you want that check at compile time. - Forgetting that a pointer-receiver method is not in the value's method set.
shortWriter{}will not compile as anio.Writer; only&shortWriter{}will. The error message names the missing method, not the receiver, which is why it confuses people. - Declaring the interface next to the implementation. A
storepackage that exportsStoreforces every consumer to importstorejust to name what it needs. Declare the one method you call, in your own package. - Interfaces with ten methods. Nobody can implement or fake them, so the "abstraction" ends up with exactly one implementation and a mock generator. Split by capability.
- Ignoring the second return value of a type assertion.
v := i.(*Rect)panics on the wrong type;v, ok := i.(*Rect)does not. Only use the one-value form when a wrong type is genuinely a bug. - Comparing interfaces whose dynamic type is a slice, map or func. It compiles and then panics with
comparing uncomparable type. Compare a field, or usereflect.DeepEqual. - Type-switching on your own interface to recover the concrete type. If you need the concrete type back, you did not want an interface there. A long type switch over your own types is a sign the behaviour belongs in a method.
- Accepting
any"for flexibility". It moves every type error to run time and tells the caller nothing. Take the narrow interface, or a type parameter. - Storing large structs in interfaces inside a hot loop. Boxing a value into an interface can copy and heap-allocate it; use a pointer, or avoid the interface in that loop.
- Assuming a nil interface is safe to call. A nil
Storepanics ons.Get(...). A typed nil with a nil-tolerant method (like(*Tally).Stringfrom the previous lesson) does not -- the difference is whether the type word is set.
Best Practices
- Keep interfaces at one or two methods, and name single-method ones after the verb:
Reader,Store,Validator. - Declare interfaces in the package that calls them; return concrete types from constructors.
- Add
var _ Iface = (*Impl)(nil)next to an implementation you intend to keep satisfying an interface -- it turns a distant call-site error into a local one. - Return
erroras the declared type, always, so a typed nil can never leak. - Reach for the
FuncType+ method trick (HandlerFunc) when a one-method interface is mostly implemented by ad-hoc functions. - Compose interfaces by embedding (
ReadWriter) instead of re-declaring methods. - Prefer generics when you need one algorithm over many shapes, and interfaces when you need one behaviour from many types.
- Wait for the second implementation before extracting an interface; Go lets you add it later with no change to the concrete type.
Practice Exercises
- Add a
cachingStoredecorator that satisfiesStore, wraps anotherStore, and records how many calls it forwarded. Prove with a counter that a repeatedidonly reaches the inner store once. - Reproduce the typed-nil trap: write
func find(id string) *MyErrthat returns nil, assign its result to anerror, and print whethererr != nil. Then fix it and explain which of the two interface words changed. - Define
type StoreFunc func(string) (string, bool)with aGetmethod so a plain closure can be passed torender. Use it to build a store that returnsstrings.ToUpper(id)for every id. - Give
shortWritera value receiver instead of a pointer receiver and record the exact compiler error at thevar _ io.Writerline. Then keep the value receiver and make it satisfyio.Writeranyway by changing what the struct holds.