System Design

G4

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.

Not startedSaved in this browser only.
  1. 1An interface value is 2 words: a type and a value. It equals nil only when both are nil.
  2. 2Define an interface where you consume it, with the fewest methods that consumer needs.
  3. 3Accept interfaces and return concrete types. Add an interface when a second implementation or a test needs one.
  4. 4A dynamic call costs nanoseconds. The larger cost is lost inlining and values that escape to the heap.
G4
    A

    The trap

    a nil that is not nil
    success that reads as failurego
    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)
    }
    1. 1The concrete result type is the bug.
    2. 2A nil *MyErr converts to error. The interface now has a type, so it is not nil.
    3. 3Compares both words. The type word is set, so this is false.
    check returnsrecorded outputstatus
    *MyErrfalse, *main.MyErrReports failure
    errortrue, <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.

    B

    The model: two words

    internal/abi/iface.go, Go 1.27
    var err errortabdata2 words, 16 bytesITab: one per interface and typeInter errorType *MyErrHash copy of the type hashFun[0] address of Errorthe valueMyErr{msg: "bad"}(*MyErr).ErrorA call loads tab, loads Fun[0], and jumps to it with data as the receiver.any has no methods, so its first word holds the type itself, with no itab.
    • 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.

    C

    When is it nil?

    recorded
    tabdata== nil
    nilniltrue
    setnilfalse
    setsetfalse

    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.

    D

    See it: the two real words

    read through unsafe in a real run
    var err error
    tabnil
    datanil
    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.

    E

    The rules: interface design

    what to do
    practicestatus
    Define it in the package that calls itApproved
    Keep it to 1 to 3 methodsApproved
    Name a one-method interface after the verb: Reader, NotifierApproved
    Return a concrete type from a constructorApproved
    Return error, not a concrete error typeApproved
    Define it beside its only implementationNot approved
    Copy every method of a struct into an interfaceNot approved
    Pass a pointer to an interfaceNot approved
    Take any as a parameterEncoders and logs only

    The consumer owns the interface. The producer ships a concrete type and never hears about it.

    F

    Defined where consumed

    tested
    signupgo
    // 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
    }
    1. 1Lives with Signup. The mail package does not import this and does not know it exists.
    2. 2Holds the interface, so a test passes a fake here.
    3. 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.

    G

    Make a function fit

    tested
    adaptergo
    // 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
    }
    1. 1Any named type can have methods, including a function type.
    2. 2The method calls the function itself.

    A function type with one method adapts any closure to the interface. net/http uses this for HandlerFunc.

    H

    Accept interfaces, return structs

    tested
    memstorego
    // 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
    1. 1Concrete: a new method needs no interface change, and go to definition works.
    2. 2A compile-time check. It costs nothing at run time.
    totalgo
    // 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
    }
    1. 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.

    I

    The rules: assertions and switches

    compiler output recorded
    formresult
    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 Readimpossible type assertion: r.(T) T does not implement io.Reader (missing method Read)
    *io.Readerr.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.

    J

    Errors through the layers

    tested
    validatego
    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
    }
    1. 1The fix from panel A: the result type is error.
    statusgo
    // 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
    }
    1. 1Go 1.26. Generic and type-safe: no target variable, and no pointer to a pointer.
    2. 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.

    K

    Optional capabilities

    tested
    flushgo
    // 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
    }
    1. 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.

    L

    Implement io.Reader

    tested with testing/iotest
    uppergo
    // 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
    }
    1. 1Process n bytes even when err is EOF.
    2. 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.

    M

    The Store in the coding kit

    tested, same interface as the kit
    storego
    type Store interface {
      Get(ctx context.Context, key string) (Item, error)1
      Update(ctx context.Context, key string, fn func(*Item) error2) (Item, error)
    }
    1. 1The memory store ignores ctx. A database store needs it.
    2. 2A rule that runs inside the lock or the transaction.
    a failing store for testsgo
    // 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
    }
    1. 1Embedding an interface promotes all of its methods. The struct satisfies Store at once.
    2. 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 askswhat changeswhat 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.

    N

    What dynamic dispatch costs

    measured with testing.B
    0.1 ns1 ns10 ns100 nsdirect call, inlined0.2 nsdirect call0.9 nsinterface call1.8 nsfunc value call3.4 nsgeneric call2.8 nsassert to concrete type1.7 nsassert to interface2.1 nsbox a small int1.2 nsbox a pointer1.2 nsbox an int11.1 ns, 1 allocbox a 32 B struct19.8 ns, 1 alloc64 B buffer, direct call3.7 ns64 B buffer, interface call21.5 ns, 1 alloc
    • 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.

    O

    Interfaces to know

    the standard library
    interfacemethodscontract to remember
    io.ReaderRead(p []byte) (int, error)May return n > 0 with an error. Handle n first.
    io.WriterWrite(p []byte) (int, error)Must return an error if n < len(p). Must not keep p.
    io.CloserClose() errorThe error can matter: a buffered file reports a failed write here.
    errorError() stringCompare with errors.Is. Never compare the text.
    fmt.StringerString() stringfmt calls it. With a pointer receiver, a value prints its fields.
    sort.InterfaceLen, Less, SwapOld form. Prefer slices.SortFunc. Learn it for sort.Reverse and container/heap.
    http.HandlerServeHTTP(w, r)One goroutine per request, so shared state needs a lock.
    context.ContextDeadline, Done, Err, ValuePass 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.

    P

    sort.Interface and its replacement

    tested
    sortgo
    // 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
      })
    }
    1. 1Index based, so sort must call through the interface for each compare.
    2. 2A generic function: no named type, and it compares values.
    3. 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.

    Q

    When an interface is premature

    decide per case
    signalverdict
    One implementation, tests run against itPremature
    An interface with the same name as its structPremature
    Added only to generate a mockFake the slow part only
    The dependency is slow or external: mail, paymentsAdd it
    Two real implementations existAdd it
    A store in a coding roundAdd 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.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.18any is an alias for interface{}. Interfaces can define type sets for constraints.A constraint interface cannot be a variable type.
    1.20errors.Join, and more than one %w. Ordinary interfaces satisfy comparable.An error can wrap several errors.
    1.21PGO can devirtualize some interface method calls.A profile can remove dispatch on hot paths.
    1.22Devirtualization and inlining now interleave. PGO devirtualizes more calls.More interface calls can inline.
    1.25reflect.TypeAssert converts a Value with no allocation.Faster than an assertion on Value.Interface.
    1.26errors.AsType: a generic errors.As.Type-safe, faster, and shorter. See panel J.
    1.27Generic 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
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe first file.Type the Store interface and MemStore. Take ctx from the start.
    buildA function can fail.Return error. Never return a concrete error type.
    buildHandlers map errors to status codes.Use one function with errors.Is and errors.AsType.
    buildThe 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.

    T

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. 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())
      }
    2. 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)
      }
    3. 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)
      }
    4. 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{})
      }
    5. 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))
      }
    6. 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)
      }
    7. 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)
      }
    8. 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)
      }
    9. 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)
      }
    10. 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)
      }
    U

    Numbers to say

    measured with testing.B
    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.