System Design

G3

Slices, maps and strings inside

These three types hold most of the data in a Go program. Each one hides a small header or a table. The traps below follow from that shape, and each output is from a real run.

Not startedSaved in this browser only.
  1. 1A slice is 3 words: a pointer, a length and a capacity. Two slices can share one array.
  2. 2Append writes in place when capacity allows. Use s[a:b:b] when you hand out a part of a slice.
  3. 3A map has no stable order and no element addresses, and concurrent writes crash the process.
  4. 4A string is immutable bytes. len counts bytes, and for range decodes runes.
G3
    A

    The trap

    b changes a
    append through a sub-slicego
    package main
    
    import "fmt"
    
    func main() {
      a := []int{1, 2, 3, 4}
      b := a[:2]1
      b = append(b, 99)2
      fmt.Println(a, b)
    }
    1. 1Len 2, and cap still 4: b can see past its own end.
    2. 2Room exists, so append writes in place. That slot is a[2].
    slice expressionrecorded a, bstatus
    a[:2][1 2 99 4] [1 2 99]a changed
    a[:2:2][1 2 3 4] [1 2 99]Approved
    • No error, no warning, and no race report. One goroutine does this.
    • The bug depends on spare capacity, so it comes and goes with input size.
    • The third index sets cap, so the next append must copy.

    A sub-slice keeps the capacity of its parent, so append writes into the parent. I set the cap with a third index.

    B

    The model: a slice header

    recorded with unsafe.SliceData, len and cap
    s := make([]int, 2, 5)datalen 2cap 5sub := s[1:]datalen 1cap 4backing array0001020304Both headers reach the same elements.Cap counts from data to the end of the array.
    expressionlencap
    s[i:j]j - icap(s) - i
    s[i:j:k]j - ik - i
    append(s, x), roomlen + 1Same, and same array
    append(s, x), no roomlen + 1Larger, and a new array
    s = s[:0]0Same: the array stays in use
    slices.Clone(s)SameAbout len, and a new array

    A slice value is a pointer, a length and a capacity. Assignment copies those 3 words and shares the array.

    C

    The rules: aliasing

    what shares, and the fix
    situationresultdo thisstatus
    Return s[:n] to a caller who appendsTheir append overwrites your datas[:n:n]Unless you own both
    Two appends from one baseBoth can write one slotslices.CloneNot approved
    A function appends to its parameterThe caller never sees the new lenReturn the sliceNot approved
    Store a slice you received in a structThe caller can still change itslices.CloneIf the caller keeps it
    Keep a small part of a large bufferThe whole buffer stays in memoryslices.CloneNot approved
    Filter in place: out := s[:0]Shares s by designClear the tail for pointersApproved
    Hold a pointer into a slice, then appendThe pointer may keep the old arrayUse an indexNot approved
    Grow with no reassignment: append(s, x)append(s, 2) (value of type []int) is not useds = append(s, x)Compiler stops it

    Whenever I hand out part of a slice, I decide if the receiver may write or append. If not, I clone or cap it.

    D

    See it: a slice, step by step

    recorded from real runs

    One array. The header of a holds a pointer, len 4 and cap 4.

    slicedatalencap
    aarray A, index 044

    array A

    1234
    a
    • inside len
    • inside cap only
    • changed by this line
    • Each state comes from a real run. Real addresses change per run, so the test maps each one to an array and an index.
    • Pick a program, then step through it. A red cell changed on that line.

    I watch for the moment len equals cap. That is when two slices stop sharing an array.

    E

    Capacity growth, measured

    2,000,000 appends, 41 reallocations for int
    1x1.25x1.5x2x1162564k64k1Mcapacity before the append256: the formula changesbyte, 1 Bint, 8 Bstring, 16 Bformula
    • Below capacity 256 the runtime doubles. Above it, new = old + (old + 768) / 4.
    • The result rounds up to an allocation size, so a real step is rarely the formula: 512 → 848 for int, and the formula gives 832.
    • Rounding depends on element size. A []string at cap 32 went to 71, not 64.
    • Appends cost O(1) on average: 41 copies to reach cap 2,064,384.
    the first appendgo
    package main
    
    import "fmt"
    
    var global []int2
    
    func main() {
      var local []int1
      local = append(local, 1)
      global = append(global, 1)
      fmt.Println(cap(local), cap(global))
    }
    1. 1This slice does not escape, so its first array can live on the stack.
    2. 2This one escapes, so the heap path gives cap 1.
    recorded: cap(local), cap(global)shell
    4 1

    Do not print cap and build a rule on it. It depends on escape analysis and on the Go version.

    Append doubles to capacity 256, then the factor falls toward 1.25. Size classes round the result up.

    F

    Cap a slice, copy to release

    tested
    prefixgo
    // Prefix returns the first n items. The third index sets cap to n, so
    // the caller's next append copies and cannot write into s.
    func Prefix[T any](s []T, n int) []T {
      return s[:n:n]1
    }
    1. 1Full slice expression. No copy happens until the first append.
    keep a small partgo
    // KeepHead copies the part it keeps. A plain data[:n] would hold the
    // whole of data in memory for as long as the result lives.
    func KeepHead(data []byte, n int) []byte {
      return slices.Clone(data[:n])1
    }
    
    // FirstField does the same for a string: a substring shares its bytes.
    func FirstField(line string) string {
      head, _, _ := strings.Cut(line, " ")
      return strings.Clone(head)2
    }
    1. 1A new array of n bytes. The large one can now be freed.
    2. 2A substring shares bytes too. The same fix applies.

    s[:n:n] protects the parent from an append. Clone also frees the parent. Which one I use depends on the lifetime.

    G

    Filter in place

    tested
    keepifgo
    // KeepIf filters in place: out shares the array of s. Clearing the tail
    // drops the pointers there, so the collector can free what they hold.
    func KeepIf[T any](s []*T, keep func(*T) bool) []*T {
      out := s[:0]1
      for _, v := range s {
        if keep(v) {
          out = append(out, v)
        }
      }
      clear(s[len(out):])2
      return out
    }
    1. 1Len 0, same array. Append overwrites slots that the loop has already read.
    2. 2The collector reads the whole array, not only up to len. Go 1.21.

    slices.DeleteFunc does this and clears the tail since Go 1.22. Prefer it in real code.

    Filtering in place allocates nothing. I clear the tail, because a pointer past len still holds its object.

    H

    Retained memory

    heap after GC, measured
    keep 16 B of 64 MBheap
    big[:16]64 MB
    Clone16 B
    s[:16]64 MB
    strings.Clone16 B

    One small sub-slice holds its whole array. I saw 64 MB held by 16 bytes.

    I

    The model: a map

    internal/runtime/maps, Go 1.27
    directory00011011Upper hashbits pick a table.tablestableup to 1024 slotstabletableone group: a control word and 8 slotsh2keyelemh2keyelemh2keyelemh2keyelemh2keyelemh2keyelememptykeyelemh2keyelem1. Hash the key. The low 7 bits are h2, and the rest pick a group.2. Compare h2 with all 8 control bytes in one operation.3. For each match, compare the full key: 1 slot in 128 matches by chance.4. No match and an empty slot: the key is absent.5. No match and no empty slot: probe the next group.A table above its limit splits in 2, so one growth step moves at most one table of 1024 slots.

    Each map has its own random hash seed, so one key lands in different slots in two maps.

    Since Go 1.24 a map is a set of Swiss tables. A control word lets one lookup check 8 slots in one step.

    J

    The rules: maps

    spec, compiler and recorded runs
    operationresultstatus
    for k := range mRandom start. Never depend on the order.Sort keys to print
    &m[k]invalid operation: cannot take address of m["a"] (map index expression of struct type T)Not approved
    m[k].n = 1cannot assign to struct field m["a"].n in mapNot approved
    delete during rangeSafe. A deleted key does not appear later.Approved
    add during rangeSafe. The new key may or may not appear.Do not depend on it
    m[math.NaN()] = 1Adds an entry that no lookup finds.Not approved
    v, ok := m[k]The only way to tell absent from zero.Approved
    touchgo
    // Touch copies the value out, changes it and stores it back. A map
    // element has no address, so m[key].Count++ does not compile.
    func Touch(m map[string]Hits, key, path string) {
      h := m[key]1
      h.Count++
      h.Last = path
      m[key] = h2
    }
    1. 1A copy. A missing key gives the zero value, which is fine for a counter.
    2. 2Store it back. A map may move its slots at any insert, so an element has no fixed address.

    A map read returns a copy. To change a struct value I store it back, or I keep pointers as values.

    K

    Concurrent writes crash

    recorded in 20 of 20 runs
    two goroutines, one mapgo
    package main
    
    import (
      "fmt"
      "time"
    )
    
    func main() {
      m := map[int]int{}
      for w := range 2 {
        go func() {
          for i := 0; ; i++ {
            m[i%8] = w1
          }
        }()
      }
      time.Sleep(10 * time.Second)
      fmt.Println("no crash")
    }
    1. 1Writes with no lock. The runtime checks a flag in the map and stops the process.
    recorded output, exit code 2shell
    fatal error: concurrent map writes

    The check is best effort, not a guarantee. A fatal error skips deferred functions, so recover never runs. -race finds races on the paths that your tests run.

    Concurrent map writes are a fatal error, and recover cannot stop it. I use a mutex and run tests with -race.

    L

    Map growth and memory

    measured
    1,000,000 int keysheap
    Full map36 MB
    After delete of every key36 MB
    After clear36 MB
    Replaced by a new map0 B
    insert 1,000timeallocs
    make(map)62.4 µs22
    make(map, 1000)15.6 µs6
    • A size hint avoids the growth steps, so it pays when you know the size.
    • A long-lived map that spikes keeps its peak size. Rebuild it after the spike.

    A map keeps its memory after delete and after clear. To release it, I replace the map.

    M

    Map or slice at small sizes

    one successful lookup, measured
    1 ns10 ns100 ns1,000 ns1248163264128256elements in the collectionslice scan, stringslice scan, intbinary search, intmap, stringmap, int
    • The exact crossover moves with machine load. The sizes in the sentence below held in every run.
    • A hash has a fixed cost, so a map at 1 element takes 4.6 ns against 1.7 ns for the scan.
    • Each scan compares about half the elements, and each string compare reads bytes. At 256, the scan takes 396 ns.
    • Binary search needs sorted data. It takes 31.9 ns at 256, against 8.6 ns for the map.

    A scan wins up to about 8 ints or 4 strings. A map wins from about 128 ints or 16 strings. Between those sizes, I choose by clarity.

    N

    The model: strings, bytes and runes

    UTF-8, and a recorded range
    runebyteindexa610éc31a92世e43b84965😀f069f7988809s[i] gives 1 byte. range gives the rune that starts at i, and skips the rest of its bytes.
    you wantusecost
    Byteslen(s), s[i]O(1)
    Rune countutf8.RuneCountInString(s)O(n), no allocation
    Each runefor i, r := range sO(n), no allocation
    Rune by index[]rune(s)[i]O(n), with a copy
    Change a bytecannot assign to s[0]Compile error: strings are immutable
    range decodesgo
    package main
    
    import "fmt"
    
    func main() {
      for i, r := range "aé世😀\xff1" {
        fmt.Printf("%d:%q ", i, r)
      }
      fmt.Println()
    }
    1. 1Not valid UTF-8. Range gives U+FFFD and moves 1 byte, and it does not panic.
    recorded outputshell
    0:'a' 1:'é' 3:'世' 6:'😀' 10:'�'

    A user-perceived character can take several runes. Go's standard library does not segment those.

    len counts bytes. for range decodes UTF-8, so i jumps, and a bad byte gives U+FFFD with width 1.

    O

    Cut text on a rune

    tested
    truncatego
    // Truncate cuts s to at most n runes. Ranging over a string yields the
    // byte offset of each rune, so the cut never lands inside a rune.
    func Truncate(s string, n int) string {
      for i := range s {1
        if n == 0 {
          return s[:i]
        }
        n--
      }
      return s
    }
    
    // Reverse works on runes. Reversing bytes would break each rune that
    // takes more than 1 byte.
    func Reverse(s string) string {
      r := []rune(s)2
      slices.Reverse(r)
      return string(r)
    }
    1. 1i is the byte offset where each rune starts, so s[:i] is always valid UTF-8.
    2. 2A conversion that allocates and copies. It is the clear way to index runes.

    I never cut a string at a byte index that I computed. Range gives me a valid offset.

    P

    strings.Builder

    tested and measured
    joingo
    // Join sizes the buffer first, so the Builder allocates once. String
    // returns the buffer with no copy, which is why a Builder must not be
    // copied after its first write.
    func Join(parts []string, sep string) string {
      n := len(sep) * max(0, len(parts)-1)
      for _, p := range parts {
        n += len(p)
      }
      var b strings.Builder
      b.Grow(n)1
      for i, p := range parts {
        if i > 0 {
          b.WriteString(sep)
        }
        b.WriteString(p)
      }
      return b.String()2
    }
    1. 1One allocation, proved in the test.
    2. 2No copy: the string reuses the buffer, and the Builder writes only past the end.
    1,000 stringstimeallocs
    s += x395 µs999
    Builder4.0 µs12
    Builder + Grow2.5 µs1

    m[string(b)] does not allocate: 0 allocations, against 1 for string(b) alone.

    += in a loop is quadratic. A Builder grows like a slice and returns its buffer with no copy.

    Q

    unique and weak

    tested
    uniquego
    // Event keeps one copy of each host in memory. The handle is one
    // pointer, so comparing two events compares two words.
    type Event struct {
      Host  unique.Handle[string]1
      Bytes int
    }
    
    func NewEvent(host string, n int) Event {
      return Event{unique.Make(host), n}
    }
    1. 1Go 1.23. Equal strings give equal handles, and == compares pointers.
    recorded: same text, other text, Valueshell
    true false go.dev
    • Use unique when millions of records repeat a few values: hosts, tenants, labels.
    • Handles do not leak: the runtime frees a value when its last handle dies.
    weakgo
    // Cache keeps a value only while someone else holds it.
    type Cache[K comparable, V any] struct {
      mu    sync.Mutex
      items map[K]weak.Pointer[V]
    }
    
    func (c *Cache[K, V]) Put(key K, v *V) {
      c.mu.Lock()
      defer c.mu.Unlock()
      if c.items == nil {
        c.items = make(map[K]weak.Pointer[V])
      }
      c.items[key] = weak.Make(v)1
      runtime.AddCleanup(v, c.drop, key)2
    }
    
    // Get returns nil when the collector has freed the value.
    func (c *Cache[K, V]) Get(key K) *V {
      c.mu.Lock()
      defer c.mu.Unlock()
      return c.items[key].Value()3
    }
    
    // drop leaves the entry alone if a newer value took the key.
    func (c *Cache[K, V]) drop(key K) {
      c.mu.Lock()
      defer c.mu.Unlock()
      if c.items[key].Value() == nil {
        delete(c.items, key)
      }
    }
    1. 1Go 1.24. This pointer does not stop the collector.
    2. 2Go 1.24. Runs after v is freed, so the entry leaves the map.
    3. 3Returns nil once the object is gone. Always check it.
    recorded: before GC, then after GCshell
    true
    <nil> true

    unique keeps one copy of equal values and gives a pointer-sized handle. weak holds a pointer that does not keep its object alive.

    R

    New in recent Go

    checked against each release's notes
    sincewhat changedwhat it means here
    1.18append uses a smoother growth formula. strings.Clone.The curve in panel E has no sudden step at the threshold.
    1.20unsafe.SliceData, String and StringData. bytes.Clone.Inspect a header with no reflect.SliceHeader.
    1.21clear, min, max. The slices and maps packages.Use slices.Clone, not a hand-written copy.
    1.22slices.Delete, DeleteFunc, Compact and Replace zero the freed tail. slices.Concat.A stale view now reads zeros.
    1.23The unique package. Iterators. slices.Repeat.Intern values with no third-party library.
    1.24Swiss table maps. The weak package and runtime.AddCleanup. strings.Lines and SplitSeq.Split a large string with no slice of parts.
    1.25More slice arrays live on the stack. unique frees values sooner.Fewer heap allocations. The cap program in panel E prints 4 and 1 on Go 1.25.9 too.
    1.26More slice arrays live on the stack, in more situations.The same change. Unsafe code that misuses a pointer can now fail.
    1.27Size-specialized allocation for objects under 80 B.Small allocations cost up to 30% less, and about 1% in real programs.
    S

    In the round

    45 minutes of build, 45 minutes of talk
    whenthe momentwhat to do or say
    buildA list endpoint returns store items.Build a new slice under the lock. A map has no order, so sort it.
    buildTests compare a list from a map.Sort first, or the test fails at random.
    buildYou know the result size.make([]T, 0, n). Say it saves 11 allocations at 1,000 items.
    buildA record has a list field.slices.Clone it on the way in and on the way out.
    talk"What does append do?"It writes in place if len is below cap. If not, it allocates, copies and returns a new header.
    talk"Why a crash, not a data race?"A map write can corrupt the table, so the runtime stops the process on purpose.
    talk"Your cache keeps growing. Why?"A map keeps its peak size after delete. Rebuild it, or bound it with eviction.
    talk"How did maps change in 1.24?"Swiss tables: groups of 8 slots with a control word, split across tables.

    I return a copy of any slice in the store. A caller then cannot change it outside the lock.

    T

    Drill

    each answer is the output of a real run

    0 of 10 known

    1. Predict the output.

      package main
      
      import "fmt"
      
      func add(s []int) {
        s[0] = 9
        s = append(s, 4)
        s[1] = 8
      }
      
      func main() {
        a := []int{1, 2, 3}
        add(a)
        b := make([]int, 3, 10)
        add(b)
        fmt.Println(a, b, len(b))
      }
    2. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        x := make([]int, 3, 4)
        y := append(x, 1)
        z := append(x, 2)
        fmt.Println(y[3], z[3])
      
        u := make([]int, 3)
        v := append(u, 1)
        w := append(u, 2)
        fmt.Println(v[3], w[3])
      }
    3. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        s := []int{1, 2, 3}
        for _, v := range s {
          s = append(s, v*10)
        }
        fmt.Println(s)
      
        arr := [3]int{1, 2, 3}
        for i, v := range arr {
          arr[2] = 10
          if i == 2 {
            fmt.Println("array:", v)
          }
        }
        sl := []int{1, 2, 3}
        for i, v := range sl {
          sl[2] = 10
          if i == 2 {
            fmt.Println("slice:", v)
          }
        }
      }
    4. Predict the output.

      package main
      
      import (
        "fmt"
        "slices"
      )
      
      func main() {
        s := []int{1, 2, 3, 4}
        t := slices.Delete(s, 1, 2)
        fmt.Println(t, s)
      }
    5. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        m := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
        orders := map[string]bool{}
        for range 200 {
          key := ""
          for k := range m {
            key += k
          }
          orders[key] = true
        }
        fmt.Println(len(orders) > 1)
        fmt.Println(m)
      }
    6. Predict the output.

      package main
      
      import (
        "fmt"
        "math"
      )
      
      func main() {
        m := map[float64]int{}
        nan := math.NaN()
        m[nan] = 1
        m[nan] = 2
        _, ok := m[nan]
        fmt.Println(len(m), ok)
        delete(m, nan)
        fmt.Println(len(m))
        clear(m)
        fmt.Println(len(m))
      }
    7. Predict the output. The first value is true if a new key was ever seen in the loop. The second is true if one was ever missed.

      package main
      
      import "fmt"
      
      func main() {
        visited, skipped := false, false
        for range 1000 {
          m := map[int]bool{1: true, 2: true, 3: true, 4: true}
          count := 0
          for k := range m {
            if k < 100 {
              m[k+100] = true
            } else {
              count++
            }
          }
          visited = visited || count > 0
          skipped = skipped || count < 4
        }
        fmt.Println(visited, skipped)
      }
    8. Predict the output.

      package main
      
      import (
        "fmt"
        "unicode/utf8"
      )
      
      func main() {
        s := "héllo"
        fmt.Println(len(s), utf8.RuneCountInString(s))
        fmt.Println(s[1], s[1:3], string(rune(s[1])))
      }
    9. Predict the output.

      package main
      
      import "fmt"
      
      func main() {
        b := []byte("hi")
        s := string(b)
        b[0] = 'H'
        fmt.Println(s, string(b))
        r := []rune("世界")
        r[0] = 'x'
        fmt.Println(len(r), string(r), len(string(r)))
      }
    10. Predict the output.

      package main
      
      import (
        "fmt"
        "strings"
      )
      
      func main() {
        var a strings.Builder
        a.WriteString("x")
        b := a
        defer func() {
          fmt.Println("recovered:", recover())
        }()
        b.WriteString("y")
        fmt.Println(b.String())
      }
    U

    Numbers to say

    measured with testing.B
    append
    1,000 items: 12 allocations and 4.9 µs; with capacity, 1 and 2.6 µs.
    map
    About 9 ns per lookup; about 38 B per int entry.
    scan
    Wins up to about 8 ints or 4 strings.
    concat
    1,000 strings: += takes 395 µs; Builder takes 4.0 µs.
    growth
    2x to cap 256, then toward 1.25x.

    Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16. Costs: median of 3 runs of 1 s. Lookups: median of 3 runs of 200 ms, on a busy machine. Use these as orders of magnitude.