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.
- 1A slice is 3 words: a pointer, a length and a capacity. Two slices can share one array.
- 2Append writes in place when capacity allows. Use s[a:b:b] when you hand out a part of a slice.
- 3A map has no stable order and no element addresses, and concurrent writes crash the process.
- 4A string is immutable bytes. len counts bytes, and for range decodes runes.
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)
}- 1Len 2, and cap still 4: b can see past its own end.
- 2Room exists, so append writes in place. That slot is a[2].
| slice expression | recorded a, b | status |
|---|---|---|
| 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.
| expression | len | cap |
|---|---|---|
| s[i:j] | j - i | cap(s) - i |
| s[i:j:k] | j - i | k - i |
| append(s, x), room | len + 1 | Same, and same array |
| append(s, x), no room | len + 1 | Larger, and a new array |
| s = s[:0] | 0 | Same: the array stays in use |
| slices.Clone(s) | Same | About 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.
| situation | result | do this | status |
|---|---|---|---|
| Return s[:n] to a caller who appends | Their append overwrites your data | s[:n:n] | Unless you own both |
| Two appends from one base | Both can write one slot | slices.Clone | Not approved |
| A function appends to its parameter | The caller never sees the new len | Return the slice | Not approved |
| Store a slice you received in a struct | The caller can still change it | slices.Clone | If the caller keeps it |
| Keep a small part of a large buffer | The whole buffer stays in memory | slices.Clone | Not approved |
| Filter in place: out := s[:0] | Shares s by design | Clear the tail for pointers | Approved |
| Hold a pointer into a slice, then append | The pointer may keep the old array | Use an index | Not approved |
| Grow with no reassignment: append(s, x) | append(s, 2) (value of type []int) is not used | s = 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.
One array. The header of a holds a pointer, len 4 and cap 4.
| slice | data | len | cap |
|---|---|---|---|
| a | array A, index 0 | 4 | 4 |
array 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.
- 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.
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))
}- 1This slice does not escape, so its first array can live on the stack.
- 2This one escapes, so the heap path gives cap 1.
4 1Do 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.
// 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
}- 1Full slice expression. No copy happens until the first append.
// 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
}- 1A new array of n bytes. The large one can now be freed.
- 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.
// 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
}- 1Len 0, same array. Append overwrites slots that the loop has already read.
- 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.
| keep 16 B of 64 MB | heap |
|---|---|
| big[:16] | 64 MB |
| Clone | 16 B |
| s[:16] | 64 MB |
| strings.Clone | 16 B |
One small sub-slice holds its whole array. I saw 64 MB held by 16 bytes.
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.
| operation | result | status |
|---|---|---|
| for k := range m | Random 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 = 1 | cannot assign to struct field m["a"].n in map | Not approved |
| delete during range | Safe. A deleted key does not appear later. | Approved |
| add during range | Safe. The new key may or may not appear. | Do not depend on it |
| m[math.NaN()] = 1 | Adds an entry that no lookup finds. | Not approved |
| v, ok := m[k] | The only way to tell absent from zero. | Approved |
// 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
}- 1A copy. A missing key gives the zero value, which is fine for a counter.
- 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.
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")
}- 1Writes with no lock. The runtime checks a flag in the map and stops the process.
fatal error: concurrent map writesThe 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.
| 1,000,000 int keys | heap |
|---|---|
| Full map | 36 MB |
| After delete of every key | 36 MB |
| After clear | 36 MB |
| Replaced by a new map | 0 B |
| insert 1,000 | time | allocs |
|---|---|---|
| make(map) | 62.4 µs | 22 |
| make(map, 1000) | 15.6 µs | 6 |
- 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.
- 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.
| you want | use | cost |
|---|---|---|
| Bytes | len(s), s[i] | O(1) |
| Rune count | utf8.RuneCountInString(s) | O(n), no allocation |
| Each rune | for i, r := range s | O(n), no allocation |
| Rune by index | []rune(s)[i] | O(n), with a copy |
| Change a byte | cannot assign to s[0] | Compile error: strings are immutable |
package main
import "fmt"
func main() {
for i, r := range "aé世😀\xff1" {
fmt.Printf("%d:%q ", i, r)
}
fmt.Println()
}- 1Not valid UTF-8. Range gives U+FFFD and moves 1 byte, and it does not panic.
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.
// 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)
}- 1i is the byte offset where each rune starts, so s[:i] is always valid UTF-8.
- 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.
// 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
}- 1One allocation, proved in the test.
- 2No copy: the string reuses the buffer, and the Builder writes only past the end.
| 1,000 strings | time | allocs |
|---|---|---|
| s += x | 395 µs | 999 |
| Builder | 4.0 µs | 12 |
| Builder + Grow | 2.5 µs | 1 |
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.
// 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}
}- 1Go 1.23. Equal strings give equal handles, and == compares pointers.
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.
// 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)
}
}- 1Go 1.24. This pointer does not stop the collector.
- 2Go 1.24. Runs after v is freed, so the entry leaves the map.
- 3Returns nil once the object is gone. Always check it.
true
<nil> trueunique keeps one copy of equal values and gives a pointer-sized handle. weak holds a pointer that does not keep its object alive.
| since | what changed | what it means here |
|---|---|---|
| 1.18 | append uses a smoother growth formula. strings.Clone. | The curve in panel E has no sudden step at the threshold. |
| 1.20 | unsafe.SliceData, String and StringData. bytes.Clone. | Inspect a header with no reflect.SliceHeader. |
| 1.21 | clear, min, max. The slices and maps packages. | Use slices.Clone, not a hand-written copy. |
| 1.22 | slices.Delete, DeleteFunc, Compact and Replace zero the freed tail. slices.Concat. | A stale view now reads zeros. |
| 1.23 | The unique package. Iterators. slices.Repeat. | Intern values with no third-party library. |
| 1.24 | Swiss table maps. The weak package and runtime.AddCleanup. strings.Lines and SplitSeq. | Split a large string with no slice of parts. |
| 1.25 | More 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.26 | More slice arrays live on the stack, in more situations. | The same change. Unsafe code that misuses a pointer can now fail. |
| 1.27 | Size-specialized allocation for objects under 80 B. | Small allocations cost up to 30% less, and about 1% in real programs. |
| when | the moment | what to do or say |
|---|---|---|
| build | A list endpoint returns store items. | Build a new slice under the lock. A map has no order, so sort it. |
| build | Tests compare a list from a map. | Sort first, or the test fails at random. |
| build | You know the result size. | make([]T, 0, n). Say it saves 11 allocations at 1,000 items. |
| build | A 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.
0 of 10 known
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)) }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]) }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) } } }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) }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) }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)) }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) }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]))) }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))) }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()) }
- 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.