Interfaces
An interface in Go is satisfied with no declaration. That lets a consumer define what it needs. The price is one trap that every Go team meets, so this sheet starts there.
- 1An interface value is 2 words: a type and a value. It equals nil only when both are nil.
- 2Define an interface where you consume it, with the fewest methods that consumer needs.
- 3Accept interfaces and return concrete types. Add an interface when a second implementation or a test needs one.
- 4A dynamic call costs nanoseconds. The larger cost is lost inlining and values that escape to the heap.
package main
import "fmt"
type MyErr struct{ msg string }
func (e *MyErr) Error() string { return e.msg }
func check(ok bool) *MyErr {1
if !ok {
return &MyErr{"bad"}
}
return nil
}
func run() error {
return check(true)2
}
func main() {
err := run()
fmt.Println(err == nil3)
fmt.Printf("%T\n", err)
}- 1The concrete result type is the bug.
- 2A nil *MyErr converts to error. The interface now has a type, so it is not nil.
- 3Compares both words. The type word is set, so this is false.
| check returns | recorded output | status |
|---|---|---|
| *MyErr | false, *main.MyErr | Reports failure |
| error | true, <nil> | Approved |
- The function succeeded, and the caller sees an error that crashes on use.
- The only change: the result type of check.
- staticcheck reports this as SA4023 when the path is visible. Run it in every build.
A typed nil in an interface is not a nil interface. I return the type error from every function that can fail.
- The compiler or the runtime builds each itab once, and caches it.
- A pointer fits in the data word. Other values live behind it, in a copy.
An interface is a pointer to an itab and a pointer to the value. The itab holds the method addresses for that pair of types.
| tab | data | == nil |
|---|---|---|
| nil | nil | true |
| set | nil | false |
| set | set | false |
No other state exists. A nil check on a concrete pointer belongs before the conversion.
Nil means no type and no value. A nil pointer inside still has a type.
var err error
- err == nil
- true
- err.Error()
- panic: runtime error: invalid memory address or nil pointer dereference
Both words are nil. This is the only state that compares equal to nil.
Rows 2 and 3 have one itab, because the pair of types is the same. Only the data word differs.
| practice | status |
|---|---|
| Define it in the package that calls it | Approved |
| Keep it to 1 to 3 methods | Approved |
| Name a one-method interface after the verb: Reader, Notifier | Approved |
| Return a concrete type from a constructor | Approved |
| Return error, not a concrete error type | Approved |
| Define it beside its only implementation | Not approved |
| Copy every method of a struct into an interface | Not approved |
| Pass a pointer to an interface | Not approved |
| Take any as a parameter | Encoders and logs only |
The consumer owns the interface. The producer ships a concrete type and never hears about it.
// Signup needs one thing from the mail system, so it says so here, in
// the package that calls it. The mail package has no interface at all.
type Notifier interface {1
Notify(ctx context.Context, user, msg string) error
}
type Signup struct {
notify Notifier2
}
func NewSignup(n Notifier) *Signup { return &Signup{notify: n} }
func (s *Signup) Register(ctx context.Context, user string) error {
if user == "" {
return errors.New("user is empty")
}
if err := s.notify.Notify(ctx, user, "welcome"); err != nil {
return fmt.Errorf("register %s: %w", user, err)3
}
return nil
}- 1Lives with Signup. The mail package does not import this and does not know it exists.
- 2Holds the interface, so a test passes a fake here.
- 3Wrapping keeps errors.Is working through the layers.
Signup needs one method, so it declares one method. Any mail client with that method fits, with no import.
// NotifierFunc makes any function a Notifier, as http.HandlerFunc does
// for handlers. A test can pass a closure and needs no type.
type NotifierFunc func1(ctx context.Context, user, msg string) error
func (f NotifierFunc) Notify(ctx context.Context, user, msg string) error {
return f(ctx, user, msg)2
}- 1Any named type can have methods, including a function type.
- 2The method calls the function itself.
A function type with one method adapts any closure to the interface. net/http uses this for HandlerFunc.
// NewMemStore returns the concrete type. A caller can use every method,
// and each consumer narrows it to the interface that it needs.
func NewMemStore() *MemStore {1
return &MemStore{items: map[string]Item{}}
}
// This line fails the build if MemStore stops satisfying Store.
var _ Store = (*MemStore)(nil)2- 1Concrete: a new method needs no interface change, and go to definition works.
- 2A compile-time check. It costs nothing at run time.
// Total reads only, so it asks for only Get. Each Store satisfies this
// with no declaration, and a test needs one method.
type getter interface {1
Get(ctx context.Context, key string) (Item, error)
}
func Total(ctx context.Context, g getter, keys []string) (int, error) {
sum := 0
for _, k := range keys {
item, err := g.Get(ctx, k)
if err != nil {
return 0, err
}
sum += item.Count
}
return sum, nil
}- 1Unexported and 1 method: all this function reads. A test fake has one method to write.
My constructor returns the struct. Each caller picks the small interface that it needs.
| form | result |
|---|---|
| v, ok := x.(T) | Ok is false on a mismatch. No panic. |
| x.(Iface) | Finds a capability at run time. |
| case int, int64: | v keeps the interface type. |
| case nil: | Only a nil interface matches. |
| err.(*MyErr) | Fails on a wrapped error. Use errors.AsType. |
| r.(T), no Read | impossible type assertion: r.(T) T does not implement io.Reader (missing method Read) |
| *io.Reader | r.Read undefined (type *io.Reader is pointer to interface, not interface) |
Cases in a switch run in order. Put the narrow interface first.
An assertion to a concrete type compares one word. An assertion to an interface asks what methods the type has.
type ValidationError struct{ Field string }
func (e *ValidationError) Error() string { return e.Field + " is invalid" }
// Validate returns the interface type, and a plain nil on success. A
// result type of *ValidationError would give callers a non-nil error.
func Validate(name string) error {1
if name == "" {
return &ValidationError{Field: "name"}
}
return nil
}- 1The fix from panel A: the result type is error.
// Status looks through wrapping. A type switch on err sees only the
// outer value, so errors.Is and errors.AsType do this job.
func Status(err error) int {
if _, ok := errors.AsType[*ValidationError](err)1; ok {
return 400
}
switch {
case err == nil:
return 200
case errors.Is(err, ErrNotFound)2:
return 404
case errors.Is(err, ErrConflict):
return 409
}
return 500
}- 1Go 1.26. Generic and type-safe: no target variable, and no pointer to a pointer.
- 2Compares each error in the chain with the sentinel.
Status maps errors to codes in one function. Wrapped errors still match, because errors.Is and AsType walk the chain.
// Flush uses an optional capability: a writer that buffers has Flush.
// Callers pass any io.Writer, and the check happens at run time.
func Flush(w io.Writer) error {
if f, ok := w.(interface{ Flush() error })1; ok {
return f.Flush()
}
return nil
}- 1An anonymous interface works in an assertion. The check runs on the dynamic type.
A wrapper hides the method. A logging ResponseWriter has no Flush unless it adds one, so http.ResponseController follows an Unwrap method.
I assert to a small interface to find an optional method. The stdlib does this for io.WriterTo and http.Flusher.
// Upper is an io.Reader that wraps another one. Use the bytes first and
// the error second, because Read can return both in one call.
type Upper struct{ R io.Reader }
func (u Upper) Read(p []byte) (int, error) {
n, err := u.R.Read(p)
for i, c := range p[:n] {1
if 'a' <= c && c <= 'z' {
p[i] = c - 'a' + 'A'
}
}
return n, err2
}- 1Process n bytes even when err is EOF.
- 2Pass the error through unchanged. io.EOF must stay io.EOF, not a wrapped one.
A Reader wraps a Reader. I use n bytes first and look at the error second, because both can arrive together.
type Store interface {
Get(ctx context.Context, key string) (Item, error)1
Update(ctx context.Context, key string, fn func(*Item) error2) (Item, error)
}- 1The memory store ignores ctx. A database store needs it.
- 2A rule that runs inside the lock or the transaction.
// FlakyStore embeds a Store and replaces one method, so a test gets a
// failing store in a few lines. Get passes through to the inner store.
type FlakyStore struct {
Store
Err error
Calls int
}
func (f *FlakyStore) Update(
ctx context.Context, key string, fn func(*Item) error,
) (Item, error) {
f.Calls++
if f.Err != nil {
return Item{}, f.Err
}
return f.Store.Update(ctx, key, fn)2
}- 1Embedding an interface promotes all of its methods. The struct satisfies Store at once.
- 2Call through to the inner store when no failure is set.
- 2 methods, so a real store and a fake are both short to write.
- A test keeps this copy equal to the one in the kit.
- Service embeds Store in the kit, so Get passes through with no code.
- FlakyStore overrides one method. Get still reaches the inner store.
| the interviewer asks | what changes | what stays |
|---|---|---|
| "Make it durable." | A Postgres store: Update becomes a transaction with a row lock. | Service, handlers, tests against Store. |
| "Add a cache." | A struct that embeds Store and overrides Get. | Every caller. |
| "How do you test a failure?" | FlakyStore in the test. | Production code. |
The Store interface is why the talk half is concrete. Postgres, a cache or a failing fake all replace MemStore with no service change.
- A direct call that inlines takes 0.2 ns. An interface call cannot inline unless the compiler proves the type.
- A local buffer passed through an interface escapes: the compiler cannot see what the callee keeps. That costs 1 allocation per call.
- Storing a pointer or a small int in an interface allocates nothing. Storing an int above 255 or a struct allocates.
- sort.Sort takes 64.3 µs for 1,000 ints, and slices.Sort takes 24.6 µs: every compare and swap in sort.Sort is a dynamic call.
An interface call costs about 1.8 ns, close to a direct call. The large costs are a lost inline and a buffer that escapes.
| interface | methods | contract to remember |
|---|---|---|
| io.Reader | Read(p []byte) (int, error) | May return n > 0 with an error. Handle n first. |
| io.Writer | Write(p []byte) (int, error) | Must return an error if n < len(p). Must not keep p. |
| io.Closer | Close() error | The error can matter: a buffered file reports a failed write here. |
| error | Error() string | Compare with errors.Is. Never compare the text. |
| fmt.Stringer | String() string | fmt calls it. With a pointer receiver, a value prints its fields. |
| sort.Interface | Len, Less, Swap | Old form. Prefer slices.SortFunc. Learn it for sort.Reverse and container/heap. |
| http.Handler | ServeHTTP(w, r) | One goroutine per request, so shared state needs a lock. |
| context.Context | Deadline, Done, Err, Value | Pass as the first parameter. See G11. |
fmt.Println(x) stores x in an any, so each argument follows the boxing rules in panel N.
I know the contract of io.Reader, error and http.Handler by heart. My code fits every library that uses them.
// ByAge is the old form: three methods, and each call goes through an
// interface. sort.Reverse wraps it by embedding sort.Interface.
type ByAge []Person
func (s ByAge) Len() int { return len(s) }
func (s ByAge) Less(i, j int) bool1 { return s[i].Age < s[j].Age }
func (s ByAge) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// SortByAge is the form to write today: no type, and no interface.
func SortByAge(p []Person) {
slices.SortStableFunc(p, func(a, b Person) int {2
return cmp.Compare(a.Age, b.Age)3
})
}- 1Index based, so sort must call through the interface for each compare.
- 2A generic function: no named type, and it compares values.
- 3Go 1.21. It avoids the overflow that a - b can give.
I use slices.SortFunc today. sort.Interface shows how embedding can override one method.
| signal | verdict |
|---|---|
| One implementation, tests run against it | Premature |
| An interface with the same name as its struct | Premature |
| Added only to generate a mock | Fake the slow part only |
| The dependency is slow or external: mail, payments | Add it |
| Two real implementations exist | Add it |
| A store in a coding round | Add it: the talk needs it |
Extracting an interface later is a small change, because the consumer can define it with no change to the producer.
I add an interface when a second implementation or a test needs one. Before that, a concrete type is simpler to read.
| since | what changed | what it means here |
|---|---|---|
| 1.18 | any is an alias for interface{}. Interfaces can define type sets for constraints. | A constraint interface cannot be a variable type. |
| 1.20 | errors.Join, and more than one %w. Ordinary interfaces satisfy comparable. | An error can wrap several errors. |
| 1.21 | PGO can devirtualize some interface method calls. | A profile can remove dispatch on hot paths. |
| 1.22 | Devirtualization and inlining now interleave. PGO devirtualizes more calls. | More interface calls can inline. |
| 1.25 | reflect.TypeAssert converts a Value with no allocation. | Faster than an assertion on Value.Interface. |
| 1.26 | errors.AsType: a generic errors.As. | Type-safe, faster, and shorter. See panel J. |
| 1.27 | Generic methods. Interface methods cannot have type parameters, and a generic method cannot implement one. | T does not implement Namer (wrong type for method Name) have Name[X any]() string want Name() string |
| when | the moment | what to do or say |
|---|---|---|
| build | The first file. | Type the Store interface and MemStore. Take ctx from the start. |
| build | A function can fail. | Return error. Never return a concrete error type. |
| build | Handlers map errors to status codes. | Use one function with errors.Is and errors.AsType. |
| build | The test needs a failing store. | Embed Store in a small struct and replace one method. |
| talk | "Why an interface here?" | The store is the part that changes in production. The service must not change with it. |
| talk | "Where would you define it?" | In the package that uses it. Go satisfies interfaces with no declaration. |
| talk | "What does an interface call cost?" | About 1.8 ns. The cost that matters is the lost inline and the escape. |
| talk | "err is not nil, but the function succeeded. Why?" | A typed nil. The interface has a type word, so the check fails. |
I wrote Store with 2 methods so that the database version is a new file, not a rewrite.
0 of 10 known
Predict the output.
package main import "fmt" type Log struct{ prefix string } func (l *Log) Name() string { if l == nil { return "no log" } return l.prefix } type Namer interface{ Name() string } func main() { var l *Log var n Namer = l fmt.Println(n.Name()) defer func() { fmt.Println("recovered:", recover()) }() n = nil fmt.Println(n.Name()) }Predict the output.
package main import ( "errors" "fmt" ) type Code int func (c Code) Error() string { return "code" } func main() { var a, b error = Code(1), Code(1) fmt.Println(a == b) fmt.Println(errors.New("x") == errors.New("x")) var c any = 1 var d any = int64(1) fmt.Println(c == d) }Predict the output.
package main import "fmt" type Box struct{ n int } func main() { b := Box{1} var v any = b b.n = 2 p := &b var w any = p b.n = 3 fmt.Println(v.(Box).n, w.(*Box).n) }Predict the output.
package main import "fmt" type A struct{} func (A) String() string { return "value method" } type B struct{} func (*B) String() string { return "pointer method" } func main() { fmt.Println(A{}, &A{}) fmt.Println(B{}, &B{}) }Predict the output. E has both Error and String.
package main import "fmt" func kind(v any) string { switch x := v.(type) { case nil: return "nil" case int, int64: return fmt.Sprintf("number %T", x) case fmt.Stringer: return "stringer " + x.String() case error: return "error " + x.Error() } return "other" } type E struct{} func (E) Error() string { return "e" } func (E) String() string { return "s" } func main() { var p *int var e error fmt.Println(kind(nil), "|", kind(int64(1))) fmt.Println(kind(E{}), "|", kind(1.5)) fmt.Println(kind(p), "|", kind(e)) }Predict the output. The columns are Flush, WriteString and Close.
package main import ( "bytes" "fmt" "io" "os" ) func describe(w io.Writer) { _, flushes := w.(interface{ Flush() error }) _, strs := w.(io.StringWriter) _, closes := w.(io.Closer) fmt.Println(flushes, strs, closes) } func main() { describe(&bytes.Buffer{}) describe(os.Stdout) }Predict the output.
package main import ( "fmt" "strings" ) type Reader interface { Read(p []byte) (int, error) Len() int } type Fake struct{ Reader } func (Fake) Len() int { return 7 } func main() { var r Reader = Fake{} fmt.Println(r.Len()) r = Fake{strings.NewReader("hi")} n, err := r.Read(make([]byte, 8)) fmt.Println(n, err, r.Len()) defer func() { fmt.Println("recovered:", recover()) }() _, err = Fake{}.Read(nil) fmt.Println(err) }Predict the output.
package main import ( "fmt" "io" ) type once struct { s string done bool } func (o *once) Read(p []byte) (int, error) { if o.done { return 0, io.EOF } o.done = true return copy(p, o.s), io.EOF } func main() { n, err := (&once{s: "hello"}).Read(make([]byte, 8)) fmt.Println(n, err) all, err := io.ReadAll(&once{s: "hello"}) fmt.Println(string(all), err) }Predict the output.
package main import ( "errors" "fmt" ) type NotFound struct{ Key string } func (e NotFound) Error() string { return e.Key + " not found" } func main() { err := fmt.Errorf("load: %w", NotFound{"a"}) _, direct := err.(NotFound) found, ok := errors.AsType[NotFound](err) fmt.Println(direct, ok, found.Key) fmt.Println(err) }Predict the output.
package main import ( "fmt" "sort" ) type byLen []string func (s byLen) Len() int { return len(s) } func (s byLen) Less(i, j int) bool { return len(s[i]) < len(s[j]) } func (s byLen) Swap(i, j int) { s[i], s[j] = s[j], s[i] } func main() { s := []string{"ccc", "a", "bb"} sort.Sort(byLen(s)) fmt.Println(s) sort.Sort(sort.Reverse(byLen(s))) fmt.Println(s) }
- call
- 0.2 ns inlined; 0.9 ns direct; 1.8 ns through an interface.
- assert
- 1.7 ns to a concrete type; 2.1 ns to an interface.
- box
- 11.1 ns and 1 allocation for an int; 1.2 ns and none for a pointer.
- escape
- 64 B buffer: 3.7 ns direct; 21.5 ns through an interface.
- sort
- 1,000 ints: 64.3 µs with sort.Sort; 24.6 µs with slices.Sort.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs of 1 s, on a busy machine. Use these as orders of magnitude.