CS Fundamentals Trainer · Guides
Go slices, arrays and maps: headers, growth, aliasing and memory retention
How slices really work and why they surprise people: the three-word header, length and capacity, how append grows (with measured capacities), aliasing through shared arrays and function arguments, preallocation (12 allocations against 1), memory retention by sub-slices and deleted pointers, and the rules for maps and range.
9 min read
Slices are the most used type in Go and the source of its most repeated bugs. The syntax looks like a dynamic array, but a slice is only a small description of a piece of an array that lives somewhere else. Once you see that, the famous surprises (an append that changes another slice, a function that modifies the caller's data, 20 MB of memory held by 200 bytes of data) stop being surprises. This guide explains the header, how append grows, how aliasing happens, how to preallocate, how memory is retained, and how maps and range fit in. The numbers were measured with Go 1.24 on a 64-bit machine; they are examples, and the exact growth steps can change between versions.
1. Arrays are values, slices are views
An array such as [3]int has its size in its type, and it is a value: assigning it or passing it copies all the elements. A slice such as []int is a three-word header: a pointer to the first element it can see, a length and a capacity. On a 64-bit machine the header is 24 bytes, whatever the number of elements.
Array [3]int | Slice []int | |
|---|---|---|
| Size is part of the type | yes | no |
| Assignment and function call | copies every element | copies the 24-byte header only |
| Elements stored | inside the variable | in a separate array, shared |
| Zero value | [0 0 0] | nil (length 0, capacity 0) |
Comparable with == | yes (if the elements are) | no, only against nil |
arr := [3]int{1, 2, 3}
arr2 := arr // a full copy
arr2[0] = 9
fmt.Println(arr, arr2) // [1 2 3] [9 2 3]
The practical rule: use slices almost everywhere, and remember that two slice variables can look at the same elements.
2. Length, capacity and slicing
len(s) is how many elements you can read. cap(s) is how many elements exist from the first one the slice sees to the end of the underlying array. Slicing s[i:j] makes a new header over the same array, with length j-i and capacity cap(s)-i.
a := []int{1, 2, 3, 4, 5}
b := a[1:3]
fmt.Println(len(b), cap(b)) // 2 4
b sees 2, 3, but it has room for two more elements, 4 and 5, because they sit in the array after it. This spare capacity is the root of most slice surprises. The three-index form s[i:j:k] sets the capacity to k-i, so you can cut off the room: a[1:3:3] has length 2 and capacity 2.
3. How append grows a slice
append writes into the spare capacity when there is some. When there is not, it allocates a bigger array, copies the elements and returns a header that points to the new array. The old array is left as it was, which is why you must write s = append(s, x) and never ignore the result.
The growth rule is: roughly double while the slice is small, then grow more slowly (about 1.25 times, plus a constant) after 256 elements, and always round the byte size up to one of the allocator's size classes. Appending one element at a time to an empty []int on Go 1.24 produced these capacities:
1 2 4 8 16 32 64 128 256 512 848 1280 1792 2560
A []byte starts at 8, because the smallest size class is 8 bytes. Appending five elements at once to a nil []int gave a capacity of 6, not 5, for the same reason. Treat the exact numbers as an implementation detail: your program should be correct for any capacity.
4. Aliasing: when two slices share an array
Two slices alias when their arrays overlap. Whether an append is visible through another slice depends on whether there was room.
a := []int{1, 2, 3, 4, 5}
b := a[1:3]
b = append(b, 99) // room for it: writes into a's array
fmt.Println(a, b) // [1 2 3 99 5] [2 3 99]
c := a[1:3:3] // capacity 2: no room
c = append(c, 77) // allocates a new array
fmt.Println(a, c) // [1 2 3 99 5] [2 3 77]
The same happens when you pass a slice to a function. The function gets a copy of the header, so changing an element is visible to the caller, but append may or may not be:
f := func(s []int) { s[0] = 100; s = append(s, 5); s[1] = 200 }
t := make([]int, 2, 2) // full: append reallocates
f(t)
fmt.Println(t) // [100 0]
t2 := make([]int, 2, 3) // one spare slot: append writes in place
f(t2)
fmt.Println(t2, t2[:3]) // [100 200] [100 200 5]
Code that behaves differently depending on capacity is a bug waiting for a different input. Two safe habits: return the new slice from functions that append, and use the full slice expression (or a copy) whenever you hand out a sub-slice that must not be extended into your data.
5. Preallocate when you know the size
Growing by append allocates and copies every time the capacity runs out. If you know, or can estimate, the final size, ask for it up front with make([]T, 0, n), or call slices.Grow(s, n) on an existing slice. Measured with testing.AllocsPerRun for 1,000 appends of an int:
| Approach | Allocations per run |
|---|---|
var s []int then append | 12 |
make([]int, 0, n) then append | 1 |
The saving is also in the copying and in the garbage that the intermediate arrays leave behind. Do not overdo it: preallocating a huge capacity "just in case" wastes memory, and a short slice that will never grow needs no help.
6. Memory retention: a small slice can hold a big array
A slice keeps its whole underlying array alive, even the part it cannot see. This is the usual cause of "my program uses far more memory than my data":
var keep [][]byte
for i := 0; i < 20; i++ {
big := make([]byte, 1<<20) // 1 MiB buffer
keep = append(keep, big[:10]) // we only wanted 10 bytes
}
// measured retained heap: 20 MB, for 200 bytes of useful data
The fix is to copy what you need so the big array can be freed: slices.Clone(big[:10]) or append([]byte(nil), big[:10]...). With that change the measured retained heap fell to almost nothing. Strings behave the same way: a substring shares the original's bytes, so strings.Clone(sub) detaches a small piece cut out of a large string.
There is a second form of the problem with pointers. If you remove an element from the middle with append(s[:i], s[i+1:]...), the old last slot still holds a pointer, and the garbage collector sees the pointed-to object as reachable. Since Go 1.22, slices.Delete zeroes the tail it frees (a test showed the slot after the new length was nil). Older code, or hand-written deletion, should do clear(tail) itself. slices.Clip(s) trims the spare capacity when you want to stop a slice from growing into memory you no longer need.
7. Maps
A map variable is a pointer to a runtime structure. Copying it, or passing it to a function, shares the same map, so a function can add keys that the caller sees without any pointer.
- The zero value is
nil. Reading from a nil map is fine and returns the zero value; writing to it panics with "assignment to entry in nil map". Create maps withmakeor a literal. - The iteration order is unspecified and randomised on purpose. Sort the keys when you need an order.
- A map is not safe for concurrent use when any goroutine writes. Use a mutex,
sync.Mapfor its narrow cases, or one owner goroutine. - A map element is not addressable:
m["a"].n++does not compile when the values are structs. Read the struct, change it, and store it back, or store pointers. make(map[K]V, n)gives a size hint that avoids early growth.clear(m)(Go 1.21) removes all keys, but the memory the map grew to is generally kept. To really release memory after a map has shrunk a lot, build a new map and copy the live entries.
8. range and copies
for i, v := range x evaluates x once. Over an array it ranges over a copy of the array; over a slice it uses the slice header, so later changes to the elements are visible:
arr := [3]int{1, 2, 3}
for i, v := range arr { arr[2] = 10; if i == 2 { fmt.Println(v) } } // 3
sl := []int{1, 2, 3}
for i, v := range sl { sl[2] = 10; if i == 2 { fmt.Println(v) } } // 10
v is always a copy of the element, so changing v changes nothing in the slice; use s[i]. Since Go 1.22 each iteration has its own i and v, so closures and goroutines that capture them see their own values (module go 1.22 or later).
9. Common mistakes
- Ignoring the result of
append. - Modifying a slice inside a function and expecting
appendto be visible to the caller. - Keeping a small sub-slice of a large buffer in a long-lived structure.
- Removing elements from a slice of pointers and leaving the old pointer behind.
- Appending in a hot loop with no preallocation when the size is known.
- Writing to a nil map, or reading and writing a map from several goroutines.
- Assuming
capafterappendis the same on every Go version. - Comparing slices with
==(useslices.Equal).
10. Things to mention in an interview
- A slice is a header (pointer, length, capacity); passing it copies the header, not the elements.
appendmay reuse the array or allocate a new one, so use its result and do not depend on which.s[i:j:k]limits capacity and is the cure for accidental overwriting through a sub-slice.- Preallocate with
make([]T, 0, n)when you know the size; measure the allocations. - A sub-slice keeps the whole array alive; copy out small pieces of big buffers.
- Maps are reference-like, random in order, unsafe for concurrent writes, and never shrink on their own.
Quick recap
Array: value, copied. Slice: a view of three words over a shared array. len is what you see, cap is what you could reach. append writes in place if it fits and reallocates if not. Copy when you must detach, preallocate when you know the size, and clear pointers you drop.
Sources
- Rob Pike, Go Slices: usage and internals and Andrew Gerrand, Arrays, slices (and strings): The mechanics of append.
- The Go Authors, Go maps in action and The Go Programming Language Specification: appending to and copying slices.
- The Go Authors, package slices (
Clone,Clip,Grow,Delete) and Effective Go: slices. - Teiva Harsanyi, 100 Go Mistakes and How to Avoid Them (Manning, 2022), chapters on slices and maps.
Practise this topic: Go