System Design

G2

Types and values

Go has one rule for passing data: it copies. Most surprises in this sheet come from what a copy shares and what it does not. Each output below is from a real run.

Not startedSaved in this browser only.
  1. 1Every assignment and every call copies. A copy of a pointer, slice or map still reaches the same data.
  2. 2Design the zero value to work. A nil slice, an unlocked mutex and an empty Buffer need no constructor.
  3. 3A pointer method needs an address. A value in an interface has none, so T does not satisfy it.
  4. 4Constants are exact until they get a type. Conversions lose bits with no error, and assertions check at run time.
G2
    A

    The trap

    the compiler accepts this
    a counter that does not countgo
    package main
    
    import "fmt"
    
    type Counter struct{ n int }
    
    func (c Counter) Inc()1 { c.n++2 }
    
    func main() {
      var c Counter
      for range 3 {
        c.Inc()3
      }
      fmt.Println("count:", c.n)
    }
    1. 1A value receiver: c is a new copy on each call.
    2. 2This changes the copy. The copy dies when Inc returns.
    3. 3Valid Go. With a pointer receiver, this same line writes (&c).Inc().
    receiverrecorded outputstatus
    (c Counter)count: 0Write lost
    (c *Counter)count: 3Approved
    • The call site looks the same in both programs. Only the receiver differs.
    • The same rule explains range values, map reads and function arguments: each one is a copy.
    • A test on the return value of Inc finds nothing, because Inc has no return value.

    A value receiver works on a copy, so the write is lost. A method that changes state takes a pointer.

    B

    The model: a struct in memory

    offsets recorded with reflect
    wasteful: 24 bytes, 10 of paddingAIDint64DScoreint32081624packed: 16 bytes, 2 of paddingIDint64Scoreint32AD0816
    • Each field sits at a multiple of its alignment. The struct size is a multiple of its largest alignment.
    • Over 1,000,000 values, the second order saves 8 MB.

    Field order sets the padding. I sort by size only for a type that exists in millions.

    C

    What a copy costs

    unsafe.Sizeof, 64-bit
    typebytes
    int8
    *T8
    map8
    chan8
    func8
    string16
    any16
    []T24
    struct{}0
    [0]int0

    A slice is 3 words, a string and an interface are 2, and a map is 1. Copying each one is cheap.

    D

    Zero values

    recorded: each row ran
    typezero valueoperationresultstatus
    []int[]int(nil)len(s), range, append[1]Safe
    []int[]int(nil)s[0]runtime error: index out of range [0] with length 0Panics
    map[string]intmap[string]int(nil)m["a"], len, range, delete0Safe
    map[string]intmap[string]int(nil)m["a"] = 1assignment to entry in nil mapPanics
    *Person(*types.Person)(nil)p == niltrueSafe
    *Person(*types.Person)(nil)p.Ageruntime error: invalid memory address or nil pointer dereferencePanics
    func()nilf()runtime error: invalid memory address or nil pointer dereferencePanics
    fmt.Stringer<nil>i.String()runtime error: invalid memory address or nil pointer dereferencePanics
    sync.Mutexunlockedmu.TryLock()trueSafe
    bytes.Bufferemptybuf.WriteStringaSafe
    strings.Builderemptysb.WriteStringaSafe
    time.Time0001-01-01 00:00:00 +0000 UTCt.IsZero()trueSafe

    A receive or send on a nil channel blocks forever. See G11 for the channel table.

    Reads on a nil slice or a nil map are safe. Writes to a nil map, and calls through nil, panic.

    E

    Make the zero value useful

    tested
    tallygo
    // Tally counts by name. Its zero value is ready to use.
    type Tally struct {
      mu     sync.Mutex1
      counts map[string]int
    }
    
    func (t *Tally) Add(name string, n int) {
      t.mu.Lock()
      defer t.mu.Unlock()
      if t.counts == nil {2
        t.counts = make(map[string]int)
      }
      t.counts[name] += n
    }
    
    // Get reads a nil map safely, so it needs no check.
    func (t *Tally) Get(name string) int {
      t.mu.Lock()
      defer t.mu.Unlock()
      return t.counts[name]3
    }
    1. 1Not a pointer. The zero Mutex is unlocked, and a value field needs no constructor.
    2. 2A lazy make, under the lock. A nil map panics on a write.
    3. 3A nil map returns 0 here, so Get needs no check.

    Nil and empty slices differ in one place: JSON. Recorded: {"items":null} and {"items":[]}.

    My type works with var t Tally. The mutex needs no setup, and the map appears on the first write.

    F

    The rules: value or pointer receiver

    per type, not per method
    the typereceiver
    Has a method that changes itPointer
    Holds a Mutex or a WaitGroupPointer
    Is large: 1 KB by value costs 15.5 ns, by pointer 1.2 nsPointer
    Is small and immutable, such as time.TimeValue
    Is a map, a func or a chanValue
    Mixes both kinds across methodsNot approved
    Uses a pointer only for speed, at 64 B or lessMeasure first

    go vet reports a copied Mutex. The sync documentation forbids a copy after first use.

    I pick one receiver kind per type. A mutex or a mutation means pointer, for every method on that type.

    G

    Method sets: why T does not satisfy the interface

    compiler output recorded
    the variabletT{n: 1}has an address: &tvar s Stringer = ttab: (Stringer, T)datacopythe hidden copyno nameT{n: 1}no address you can takeA pointer method needs a *T. The only T here is the hidden copy.A write through that pointer would change the copy, and t would stay the same.So the method set of T excludes pointer methods. Store &t instead.
    method onT in interface*T in interfacevariable x.M()m[k].M()
    (t T)YesYesYesYes
    (t *T)NoYesYesNo
    • x.M() works on a variable because the compiler writes (&x).M(). A variable is addressable.
    • A map element and a function result are not addressable, so the call fails. A slice element is addressable.
    what the compiler saysshell
    cannot use T{…} (value of struct type T) as fmt.Stringer value in variable
    declaration: T does not implement fmt.Stringer (method String has pointer
    receiver)
    
    cannot call pointer method Inc on T

    The method set of T has only value methods. A value in an interface is an unnamed copy, so it cannot give a pointer method an address.

    H

    Both receivers in one design

    tested
    money and accountgo
    // Money is small and immutable, so it uses value receivers.
    type Money struct {
      Cents    int64
      Currency string
    }
    
    func (m Money) Add(o Money) Money {1
      m.Cents += o.Cents
      return m
    }
    
    func (m Money) String() string {
      return fmt.Sprintf("%d.%02d %s", m.Cents/100, m.Cents%100, m.Currency)
    }
    
    // Account holds a mutex and changes, so every method uses a pointer.
    type Account struct {
      mu      sync.Mutex
      balance Money
    }
    
    func (a *Account) Deposit(m Money) {2
      a.mu.Lock()
      defer a.mu.Unlock()
      a.balance = a.balance.Add(m)
    }
    
    func (a *Account) Balance() Money {
      a.mu.Lock()
      defer a.mu.Unlock()
      return a.balance
    }
    1. 1The copy is safe to change. The result carries the sum, and the caller keeps its value.
    2. 2A value receiver would copy the lock and lose the write.

    Money is a value: Add returns a new one. Account holds a lock, so it is always behind a pointer.

    I

    Embedding

    tested
    embeddinggo
    type Base struct{ ID string }
    
    func (b Base) Kind() string { return "base" }
    
    // Label calls Base.Kind, whatever type embeds Base.
    func (b Base) Label() string1 { return b.Kind() + ":" + b.ID }
    
    type User struct {
      Base
      Email string
    }
    
    // Kind hides Base.Kind for callers that hold a User.
    func (u User) Kind() string3 { return "user" }
    
    // Label must be written again to use the new Kind.
    func (u User) Label() string { return u.Kind() + ":" + u.ID }
    1. 1The receiver is a Base. This call to Kind always means Base.Kind.
    2. 2The field name is Base. Its fields and methods are promoted to User.
    3. 3The shallower name wins. u.Base.Kind() still reaches the inner one.
    • Two embedded types with one field name compile, but using that name does not.
    • Do not embed sync.Mutex in an exported struct. Lock becomes part of its API.

    Embedding is delegation, not inheritance. An inner method calls inner methods and never reaches the outer type.

    J

    iota and enums

    tested
    enumgo
    type Status int
    
    const (
      StatusUnknown Status = iota1 // The zero value means "not set".
      StatusOpen
      StatusPaid
      StatusVoid
    )
    
    var statusNames = [...]string{"unknown", "open", "paid", "void"}
    
    func (s Status) String() string {
      if s < 0 || int(s) >= len(statusNames) {2
        return "Status(" + strconv.Itoa(int(s)) + ")"
      }
      return statusNames[s]
    }
    
    type Bytes int64
    
    const (
      _        = iota3
      KB Bytes = 1 << (10 * iota)4
      MB
      GB
    )
    1. 1Zero is the value of an unset field. Keep it invalid on purpose.
    2. 2Nothing stops Status(9): a Go enum is only a named integer.
    3. 3Blank skips iota 0, so KB uses iota 1.
    4. 4MB and GB repeat this expression with the next iota.

    My enum starts with an unknown value at zero, so a missing field reads as not set, not as a real state.

    K

    The rules: constants

    drill and compiler output
    codemeaning
    const big = 1 << 100Untyped and exact. It must fit the type where you use it.
    5 / 2, 5 / 2.02, then 2.5. The operands set the kind of division.
    2 * time.Second2 takes type Duration, so this compiles.
    n * time.Secondn * time.Second (mismatched types int and time.Duration)
    time.Duration(n) * time.SecondThe fix: an explicit conversion.
    x := 1.5A variable needs a type, so it takes the default: float64.
    uint8(300)constant 300 overflows uint8

    Default types: int, float64, rune, complex128, string, bool.

    An untyped constant takes the type its use needs. A variable never changes type, so I convert it by hand.

    L

    Conversions and assertions

    two different tools
    formcheckedon failure
    T(x), numbersCompile timeKeeps the low bits, with no error. Check the range first.
    []byte(s), string(b)Compile timeCannot fail. Each one copies the bytes.
    [4]int(s)Run timePanics if the slice is too short.
    v, ok := x.(T)Run timeok is false, and v is the zero value.
    v := x.(T)Run timePanics.
    switch v := x.(type)Run timeThe default case runs.

    An assertion works only on an interface value, and it matches the exact dynamic type. See G4.

    A conversion changes the type at compile time. An assertion reads the dynamic type at run time and can fail.

    M

    Assertions on decoded JSON

    tested
    intfieldgo
    // IntField reads a number from JSON decoded into map[string]any.
    // encoding/json stores every number as float64, so .(int) never matches.
    func IntField(m map[string]any, key string) (int, error) {
      switch v := m[key].(type) {1
      case nil:2
        return 0, fmt.Errorf("%s missing: %w", key, ErrField)
      case float64:
        if v != math.Trunc(v) {3
          return 0, fmt.Errorf("%s is %v: %w", key, v, ErrField)
        }
        return int(v), nil
      default:
        return 0, fmt.Errorf("%s is %T: %w", key, v, ErrField)
      }
    }
    1. 1One expression covers every case. In each case, v has that type.
    2. 2A missing key gives a nil interface, so this case catches it.
    3. 3A float converted to int cuts the fraction. Refuse it instead.
    narrowgo
    // ToInt32 checks first, because a conversion cuts the high bits and
    // reports nothing.
    func ToInt32(n int64) (int32, error) {
      if n < math.MinInt32 || n > math.MaxInt32 {
        return 0, fmt.Errorf("%d: %w", n, ErrRange)
      }
      return int32(n), nil1
    }
    1. 1Safe here, after the range check.

    JSON numbers decode to float64 in an any, so an assertion to int always fails. I switch on the real type.

    N

    Comparability

    recorded
    type==map key
    Numbers, strings, bools, pointers, chansYesYes
    Struct or array of comparable partsYesYes
    Slice, map, funcCompile errorCompile error
    InterfacePanics on a slice insidePanics on a slice inside
    Struct with a float fieldNaN never equals NaNNaN key is unreachable
    time.TimeUse t.EqualConvert to Unix first
    a == b and &a == &b, an array with NaN, a struct keyshell
    true false
    false
    found

    time.Time == compares the location and the monotonic reading too, not only the instant.

    comparablego
    // Key is comparable, so it works as a map key with no string building.
    type Key struct {1
      Tenant string
      ID     int
    }
    
    // Dedupe keeps the first of each value. T must support ==.
    func Dedupe[T comparable]2(in []T) []T {
      seen := make(map[T]struct{}, len(in))
      out := in[:0:0]3
      for _, v := range in {
        if _, dup := seen[v]; dup {
          continue
        }
        seen[v] = struct{}{}
        out = append(out, v)
      }
      return out
    }
    1. 1A struct key needs no string building, and two fields cannot run together.
    2. 2Since Go 1.20 an interface also satisfies this, so T = any compiles and can panic on a slice.
    3. 3An empty slice with cap 0: the first append allocates, so Dedupe keeps its input intact. See G3.

    Structs, arrays and pointers compare with ==. Slices, maps and funcs do not. An interface compiles, and it can panic at run time.

    O

    Array or slice

    per property
    [3]int[]int
    LengthPart of the typeRun time
    AssignmentCopies every elementCopies 3 words, shares elements
    == and map keyYesNo
    Can growNoYes
    Zero valueAll elements zeronil
    Good for[32]byte hash, fixed tablesEverything else

    sha256.Sum256 returns [32]byte, so a digest works directly as a map key.

    An array is a value with its length in the type. I use one for fixed keys such as a hash, and a slice everywhere else.

    P

    new(expr) for optional fields

    tested, Go 1.26
    patchgo
    // Patch tells "leave it alone" (nil) from "set to zero" (a pointer to 0).
    type Patch struct {
      Name *string `json:"name,omitempty"`
      Age  *int    `json:"age,omitempty"`1
    }
    
    func (p Patch) Apply(to *Person) {
      if p.Name != nil {
        to.Name = *p.Name
      }
      if p.Age != nil {
        to.Age = *p.Age
      }
    }
    
    // Birthday builds a patch from a computed value in one expression.
    func Birthday(u Person) Patch { return Patch{Age: new(u.Age + 1)2} }
    1. 1nil: leave it alone. A pointer to 0: set it to 0. An int cannot say both.
    2. 2Go 1.26: new takes an expression. It allocates, stores the value and returns the pointer.
    recorded: new(x + 1), new(x), new(int), x, then JSON for absent and for new(0)shell
    2 9 0 1
    {"name":"a"}
    {"name":"b","age":0}

    A pointer field separates absent from zero. new(expr) builds that pointer in one expression.

    Q

    See it: what an assignment copies

    recorded from real runs
    1. a := 1
    2. b := a
    3. b = 2
    a1
    bnot declared
    The assignment copies 8 bytes. Step to the write.
    • Pick a kind of value, then step through the assignment and the write.
    • The slice row with append changes only b: the array had no spare room, so b moved. G3 shows the steps.
    • A string has no write operation. += builds a new string, so the shared bytes stay safe.

    Assignment copies the top level. A pointer, slice or map inside still points at the same data, so a deep copy is my job.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.20Slice to array conversion: [4]byte(x). unsafe.SliceData, String and StringData. Ordinary interfaces satisfy comparable. Struct compare stops at the first mismatch, by spec.A generic map key can now be any, with a run-time panic as the price.
    1.21Built-ins min, max and clear.clear zeroes a slice or empties a map.
    1.22Each loop iteration creates new variables. Range over an integer.A pointer to a range variable now differs per iteration.
    1.23Range over functions.Your own types can work with for range.
    1.24Generic type aliases.A library can rename a generic type with no break.
    1.25No language change. The spec drops core types.Read older posts on core types with care.
    1.26new takes an expression. A generic type can refer to itself in its type parameters.Optional fields need no helper function. See panel P.
    1.27Generic methods. A struct literal key can be any valid field selector. Function type inference applies to all assignments to a matching function type.Interface methods still cannot have type parameters, and a generic method cannot implement one.
    a generic method, Go 1.27go
    package main
    
    import "fmt"
    
    type Bag map[string]any
    
    func (b Bag) As[T any]1(key string) (T, bool) {
      v, ok := b[key].(T)
      return v, ok
    }
    
    func main() {
      b := Bag{"n": 7, "s": "hi"}
      fmt.Println(b.As[int]("n"))
      fmt.Println(b.As[string]("n"))
    }
    1. 1The method declares its own type parameter.
    recorded outputshell
    7 true
     false
    a promoted field as a key, Go 1.27go
    package main
    
    import "fmt"
    
    type Base struct{ ID int }
    
    type User struct {
      Base
      Name string
    }
    
    func main() {
      u := User{ID: 71, Name: "a"}
      fmt.Println(u.ID, u.Base, u)
    }
    1. 1ID belongs to the embedded Base. Older Go needs User{Base: Base{ID: 7}}.
    recorded outputshell
    7 {7} {{7} a}
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildThe store holds records in a map.Use map[string]Item and return Item by value. The copy leaves the lock safely.
    buildItem gets a slice field.Clone it before you return, because a struct copy shares the slice.
    buildA struct has a mutex.Use pointer receivers on every method, and pass &store.
    buildA PATCH body has optional fields.Use pointer fields, so 0 and absent stay different.
    buildA record has a state.Use a named int with iota, a String method, and an unknown value at zero.
    talk"Value or pointer here?"Say what must be shared, then the size. Quote the numbers in panel U.
    talk"Why does this not satisfy the interface?"The method has a pointer receiver, so only *T has it in its method set.
    talk"Is a pointer faster?"Not by default. It can move the value to the heap: 19.2 ns against 6.7 ns.

    I return values from the store, so no caller can change data outside the lock.

    T

    Drill

    each answer is the output of a real run

    0 of 12 known

    1. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        var m map[string]int
        v, ok := m["a"]
        fmt.Println(v, ok, len(m))
        delete(m, "a")
        for range m {
          fmt.Println("never")
        }
        fmt.Println("reads are safe")
        m["a"] = 1
        fmt.Println("after the write")
      }
    2. Predict the output.

      package main
      
      import "fmt"
      
      type Item struct{ Qty int }
      
      func main() {
        items := []Item{{1}, {2}}
        for _, it := range items {
          it.Qty *= 10
        }
        fmt.Println(items)
        for i := range items {
          items[i].Qty *= 10
        }
        fmt.Println(items)
      }
    3. Predict the output.

      package main
      
      import "fmt"
      
      func bump(a [3]int) { a[2] = 100 }
      
      func main() {
        a := [3]int{1, 2, 3}
        b := a
        b[0] = 9
        s := a[:]
        s[1] = 7
        bump(a)
        fmt.Println(a, b, s)
      }
    4. Predict the output.

      package main
      
      import "fmt"
      
      type Doc struct {
        Title string
        Tags  []string
        Meta  map[string]int
      }
      
      func main() {
        a := Doc{"a", []string{"x"}, map[string]int{"v": 1}}
        b := a
        b.Title = "b"
        b.Tags[0] = "y"
        b.Meta["v"] = 2
        b.Tags = append(b.Tags, "z")
        fmt.Println(a)
        fmt.Println(b)
      }
    5. Predict the output.

      package main
      
      import "fmt"
      
      type V struct{ n int }
      
      func (v V) Val() int  { return v.n }
      func (v *V) Ptr() int { return v.n }
      
      func main() {
        v := V{1}
        f, g := v.Val, v.Ptr
        v.n = 2
        fmt.Println(f(), g())
      }
    6. Predict the output.

      package main
      
      import "fmt"
      
      type Base struct{}
      
      func (Base) Name() string { return "base" }
      func (b Base) Hello() string {
        return "hello from " + b.Name()
      }
      
      type Child struct{ Base }
      
      func (Child) Name() string { return "child" }
      
      func main() {
        c := Child{}
        fmt.Println(c.Name())
        fmt.Println(c.Hello())
        fmt.Println(c.Base.Name())
      }
    7. Predict the output.

      package main
      
      import "fmt"
      
      const (
        A = iota * 10
        B
        _
        C
        D = "x"
        E
        F = iota
      )
      
      const G = iota
      
      func main() {
        fmt.Println(A, B, C, D, E, F, G)
      }
    8. Predict the output.

      package main
      
      import "fmt"
      
      const big = 1 << 100
      
      func main() {
        fmt.Println(big >> 98)
        fmt.Println(5/2, 5/2.0)
        fmt.Println(0.1+0.2 == 0.3)
        a, b := 0.1, 0.2
        fmt.Println(a+b == 0.3)
      }
    9. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        n, big := 300, 1<<40
        f := -1.9
        fmt.Println(uint8(n), int8(n))
        fmt.Println(int32(big), int(f))
        fmt.Println(string(rune(0x4E16)), []byte("é"))
      }
    10. Predict the output.

      package main
      
      import "fmt"
      
      type ID int
      
      func main() {
        var v any = ID(7)
        _, isInt := v.(int)
        id, isID := v.(ID)
        fmt.Println(isInt, id, isID, int(id)+1)
        defer func() {
          fmt.Println("recovered:", recover())
        }()
        fmt.Println(v.(string))
      }
    11. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        var a, b any = 1, 1
        fmt.Println(a == b)
        a, b = []int{1}, 1
        fmt.Println(a == b)
        a, b = []int{1}, []int{1}
        defer func() {
          fmt.Println("recovered:", recover())
        }()
        fmt.Println(a == b)
      }
    12. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        s := []int{1, 2, 3}
        a := [2]int(s)
        p := (*[2]int)(s)
        s[0] = 9
        fmt.Println(a, *p)
        defer func() {
          fmt.Println("recovered:", recover())
        }()
        fmt.Println([4]int(s))
      }
    U

    Numbers to say

    measured with testing.B
    8 B
    1.2 ns by value; 1.3 ns by pointer.
    64 B
    1.8 ns by value; 1.3 ns by pointer.
    1 KB
    15.5 ns by value; 1.2 ns by pointer.
    return
    6.7 ns by value; 19.2 ns and 1 allocation by pointer.
    words
    Slice 24 B; string and interface 16 B; map and pointer 8 B; struct{} 0 B.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 runs of 1 s, on a busy machine. Each call stays out of line. Use these as orders of magnitude.