Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Interfaces: Implicit Implementation, Type Assertions, and Type Switches

Implicit interface satisfaction in Go: method sets and receiver kinds, type assertions versus type switches, the typed-nil interface, and the compile errors that name the missing method.

~5 min readGo
#Go#Interfaces#Backend
An abstract interface socket accepting matching struct blocks with teal accents

A Go interface is a method set, and nothing else. A type satisfies it by having those methods with exactly those signatures — there is no implements clause, no registration, and no import of the interface's package at the point where the type is defined. That single design decision is why io.Reader works with files, buffers, network connections and test doubles without any of them knowing it exists, and it is also why the compiler can reject an assignment with a message that names the one method you are missing.

Quick Summary

  • Satisfaction is structural and implicit: the method set of the type must contain every method of the interface with an identical signature. Nothing is declared.
  • Receiver kind is part of the method set. If Read has a pointer receiver, *T implements io.Reader and T does not.
  • An interface value holds a type and a value. A nil interface has neither; an interface holding a nil pointer has both, and is not equal to nil.
  • v := x.(T) panics when the dynamic type is not T; v, ok := x.(T) reports it. x.(type) is legal only inside a type switch.
  • Asserting to an interface checks the method set; asserting to a concrete type requires the dynamic type to be exactly that type.
  • Interfaces are for behaviour at the call boundary. Accept them as parameters, return concrete types from constructors.

Basic syntax and type signatures

go
type Reader interface { Read(p []byte) (n int, err error) } type Writer interface { Write(p []byte) (n int, err error) } // Embedded interfaces compose: ReadWriter needs both method sets. type ReadWriter interface { Reader Writer } // Implicit implementation: no declaration anywhere links Counter to Writer. type Counter struct{ n int } func (c *Counter) Write(p []byte) (int, error) { c.n += len(p) return len(p), nil } func main() { var w Writer = &Counter{} // *Counter has Write, so it satisfies Writer // var bad Writer = Counter{} // compile error: Write has pointer receiver fmt.Fprintf(w, "hello") // any Writer works, including bytes.Buffer and os.Stdout }

The empty interface, now spelled any (an alias since Go 1.18), has an empty method set, so every type satisfies it. That also makes it the least informative type in the language: once a value is in an any, the only things you can do with it are type assertion, type switch, and reflection.

Type assertions and type switches are the two ways back out:

go
func describe(x any) string { // Comma-ok form: no panic, safe for untrusted input. if s, ok := x.(string); ok { return "string of length " + strconv.Itoa(len(s)) } switch v := x.(type) { case int, int64: // Multiple types in one case: v keeps the static type of x (any). return fmt.Sprintf("integer family: %v", v) case []byte: // Single type in a case: v is []byte here. return fmt.Sprintf("bytes: %d", len(v)) case nil: return "nil interface" default: return fmt.Sprintf("other: %T", v) } }

Assertions, conversions, and switches side by side

ExpressionChecksOn failureStatic type of result
x.(T)dynamic type is exactly Tpanic: interface conversion: any is string, not intT
v, ok := x.(T)samev is the zero value, ok is falseT
x.(I)method set contains I's methodspanic, same shape as aboveI
v, ok := x.(I)samezero value, ok falseI
switch v := x.(type)one branch per distinct dynamic typedefault branch; no panicper branch
T(v) (conversion)convertibility rules, no runtime checkcompile error if not convertibleT
any(v) (boxing)always succeedsneverany

The distinction between the first and third rows is worth memorising: asserting to a concrete type is an identity check on the dynamic type, while asserting to an interface is a capability check. x.(fmt.Stringer) succeeds for anything with a String() string method, including types in packages that have never heard of fmt; x.(MyStringer) only if the dynamic type is MyStringer, which for an interface target means the same capability check, and for a struct type means exact identity.

Practical edge cases and deep dives

1. The typed-nil interface that is not nil

go
type QueryError struct{ Code int } func (e *QueryError) Error() string { return fmt.Sprintf("query failed: %d", e.Code) } func lookup() error { var qerr *QueryError // nil *QueryError if false { qerr = &QueryError{Code: 500} } return qerr // BUG: returns a non-nil error interface holding a nil pointer } func main() { err := lookup() fmt.Println(err == nil) // false fmt.Printf("%T %v\n", err, err) // *main.QueryError <nil> if err != nil { fmt.Println(err.Error()) // panics: nil pointer dereference inside Error } }

An interface value is a pair: a type word and a data word. Returning a nil *QueryError stores a type (*QueryError) and a nil data pointer, so the interface is non-nil while the pointer inside is nil. The fix is to return the interface's nil explicitly:

go
func lookup(id string) error { var qerr *QueryError if err := run(id, &qerr); err != nil { return err } if qerr != nil { return qerr // only box when the pointer is real } return nil }

The same trap appears in errors.As results, in http.Handler wrappers, and in any constructor that returns an interface while building a pointer.

2. Method sets, embedding, and addressability

go
type Base struct{ id string } func (b Base) ID() string { return b.id } // value receiver func (b *Base) Rename(s string) { b.id = s } // pointer receiver type Wrapped struct { Base // embedded value } type Namer interface{ ID() string } type Renamer interface{ Rename(string) } func main() { var n Namer = Wrapped{} // ok: ID is in Wrapped's method set _ = n // var r Renamer = Wrapped{} // error: Rename has a pointer receiver var r Renamer = &Wrapped{} // ok: *Wrapped has both methods _ = r s := Wrapped{} s.Rename("x") // ok: s is addressable, so (&s).Rename("x") Wrapped{}.Rename("x") // compile error: cannot call pointer method on Wrapped{} // m := map[string]Wrapped{}; m["a"].Rename("x") // cannot call pointer method on m["a"] p := &s p.Rename("y") // same method, no copy }

The compiler inserts & only for addressable operands: a variable, a pointer dereference, a slice element, or a field of an addressable struct. Map elements, function results, and composite literals are not addressable, which is why mutating a struct stored in a map needs m["a"] = updated after a copy-and-modify, or a map of pointers.

Embedding promotes both fields and methods, and the depth rules decide ambiguity: two embedded types with a Name field at the same depth make s.Name a compile error (ambiguous selector), while a shallower Name on the outer struct wins silently. That is not inheritance — the outer type does not become the inner type, and var b Base = s does not compile. It is composition with syntactic promotion.

3. Type switches over interfaces and nil cases

go
func closeIfPossible(v any) error { // Capability check: does the value have Close()? if c, ok := v.(io.Closer); ok { return c.Close() } return nil } func kind(v any) string { switch v.(type) { case nil: return "nil" // only reachable when the interface itself is nil case error: return "error" // interface case: matches the method set case interface{ Timeout() bool }: return "timeout-capable" default: return fmt.Sprintf("%T", v) } }

Two details matter here. A case nil branch only matches a nil interface, not an interface holding a nil pointer — the typed-nil value falls into its own type case, which is another way the pair representation surfaces. And case order is significant: the first matching type wins, so case error before a more specific interface swallows everything that implements error, including the timeout-capable type below it.

Assertions to interfaces are also how Go does optional capabilities without a combinatorial interface hierarchy: io.ReaderFrom, http.Flusher, interface{ Unwrap() []error } in errors. Each is a small interface tested at the point of use, which keeps the concrete types free of declarations.

4. Equality, comparability, and what an interface cannot hold

go
func main() { var a any = []int{1, 2} var b any = []int{1, 2} // fmt.Println(a == b) // panic: comparing uncomparable type []int var c any = 42 var d any = 42 fmt.Println(c == d) // true: same type, same value type Pair struct{ X, Y int } var e any = Pair{1, 2} fmt.Println(e == Pair{1, 2}) // true: structs of comparable fields compare by value }

Interface equality compares the dynamic types first and then the values, so two different types that both satisfy the interface are never equal even when they print the same. If the dynamic type is not comparable — a slice, map, or func — the comparison panics at runtime rather than compiling to false. That is why errors.Is compares with == only after checking that the target's type is comparable, and why putting structs with slice fields into a map[any]bool key is a runtime panic waiting for the first duplicate.

Common mistakes and compiler errors

ErrorMessageCauseFix
compileT does not implement I (method M has pointer receiver)assigning a value where the method requires a pointer receiverassign &T{} or change the receiver
compileimpossible type assertion: T does not implement I (missing method M)asserting a concrete type to an interface it cannot satisfyfix the type or the interface; this one is always a bug
compilecannot call pointer method on m[k] / cannot take the address of xmutating a non-addressable operandcopy to a variable, or store pointers
compileinvalid operation: a == b (struct containing []int cannot be compared)comparing a struct with an uncomparable fieldcompare field by field, or use reflect.DeepEqual
compileambiguous selector s.Nametwo embedded fields at the same depth provide Namequalify with the embedded type, or remove one
panicinterface conversion: interface {} is string, not intsingle-value assertion faileduse the comma-ok form
panicinvalid memory address or nil pointer dereferencetyped-nil interface, or a nil pointer receiverreturn an untyped nil, or guard the receiver
paniccomparing uncomparable type []int== on interfaces holding slices or mapscompare with reflect.DeepEqual or a key field

The pattern behind the first three rows is that interfaces describe behaviour, while receivers decide which value provides it. When a method needs to mutate, the receiver is a pointer, and every holder of that behaviour must hold a pointer too. Deciding the receiver kind once, at the type's definition, is cheaper than discovering the mismatch at every assignment site later.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.