Arrays, Slices & Maps: make, append, capacity, aliasing, range
"A slice is a descriptor for a contiguous segment of an underlying array and provides access to a numbered sequence of elements from that array." — The Go Programming Language Specification, "Slice types" (language version go1.27)
Summary: Go has one fixed-size value type (the array), one view type on top of it (the slice: pointer, length, capacity) and one built-in hash table (the map); almost every surprising bug with them comes from two slices sharing a backing array or from treating a map as ordered or thread-safe. Focus: Arrays as values, the slice header, make, append and its growth factor, aliasing, full slice expressions, copy, memory leaks through sub-slices, nil vs empty, the slices and maps packages and their iterators, sorting and stability, strings as bytes, multi-dimensional layouts, map internals (buckets to Swiss tables), iteration order, delete/clear, NaN keys, concurrent map writes, sync.Map, and preallocation. Learning goal: Predict for any append, slice expression or map operation whether memory is shared, copied or reallocated, and write code that stays correct when someone else appends to your result or reads your map from another goroutine.
This page is the complete reference for Go's three built-in collection types as a backend developer meets them: in request handlers, batch jobs, caches and JSON APIs. It owns arrays, slices, maps, the slices/maps/bytes helpers and their performance characteristics. It does not re-teach neighbours: pointers and escape analysis are in Pointers & Memory Model Basics; the for/range statement itself and the Go 1.22 loop-variable change are in Control Flow; type parameters and constraints (cmp.Ordered, ~[]E) are in Generics; runes, UTF-8 and strings are in Strings, Runes, fmt Verbs; mutexes and sync.Map internals are in sync & atomic; the race detector in depth is in Race Conditions; and JSON tags and encoders are in JSON, XML, Struct Tags.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has three collection types and not one | Why it exists |
| Go 1.0 to Go 1.24: who added what, and when | Where it comes from |
[N]T, value semantics, == on arrays | Arrays are values |
| Pointer, length, capacity | The slice header |
make([]T, len, cap), literals, zero values | make, literals and the zero value |
How append grows: 2x, then towards 1.25x | append and the growth factor |
| Two slices, one array, silent overwrites | Aliasing |
s[low:high:max] | Full slice expression |
copy(dst, src), overlapping copies | copy semantics |
s[:0], in-place filters, reused buffers | Reuse with s[:0] |
| A 3-byte slice keeping 64 MiB alive | Memory leaks through sub-slices |
null vs [] in JSON | nil slice vs empty slice |
slices.Sort, BinarySearch, Compact, Delete, Insert, Concat… | The slices package |
slices.All, Values, Collect, Sorted | Iterators |
sort.Slice vs slices.Sort, stable sort | Sorting and stability |
[]byte(s), bytes.Buffer, append(b, s...) | Strings as byte slices |
[][]T, [N][M]T, flat grids | Multi-dimensional data |
| Zero-value reads, comma-ok, sets | Maps |
| Buckets, load factor, Swiss tables (Go 1.24) | Map internals |
Why range over a map changes order | Iteration order |
delete during range, clear, m[k].f = v | Mutating maps |
| Which types can be keys, NaN | Map key types and NaN |
fatal error: concurrent map writes, sync.Map | Maps and goroutines |
maps.Keys, Values, Clone, Equal, Collect | The maps package |
slices.Equal, maps.Equal, reflect.DeepEqual | Comparing |
| Preallocation, value vs pointer elements | Performance |
| Every panic and compile error verbatim | Mechanics |
| Fixes with tested code | Solving the classic problems |
| Coming from PHP arrays | For PHP/Laravel developers |
| Monolith to distributed system | In architecture |
| Reproduce everything on your laptop | Lab |
| Wrong beliefs, cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The three types. Each row is unpacked in the concept catalogue.
| Type | In plain words | Zero value | Assignment / call copies | Comparable with == | Usable as map key |
|---|---|---|---|---|---|
Array [N]T | N elements in a row; N is part of the type | N zero elements (usable) | All N elements | Yes, if T is | Yes, if T is |
Slice []T | A window (ptr, len, cap) onto an array | nil (len 0, appendable) | Only the 24-byte header; elements are shared | Only with nil | No |
Map map[K]V | A hash table from keys to values | nil (readable, NOT writable) | Only the pointer; entries are shared | Only with nil | No |
String string | A read-only byte slice (ptr, len) | "" | Only the header; bytes are immutable | Yes | Yes |
The built-ins and helpers you use daily.
| Operation | What it does | Allocates? | Trap |
|---|---|---|---|
make([]T, n) | len n, cap n, all zero | Yes (or on stack if it does not escape) | append adds AFTER the n zeros |
make([]T, 0, n) | len 0, cap n | Yes | Index s[0] panics until you append |
append(s, x...) | Writes in place if it fits, else grows | Only when len+n > cap | Result may or may not share s's array |
s[a:b] | New header, same array, cap = cap(s)-a | No | Appends reach into s[b:] |
s[a:b:c] | Same, but cap = c-a | No | c must be ≤ cap(s) |
copy(dst, src) | Copies min(len(dst), len(src)) elements | No | Copies nothing into a zero-length dst |
clear(s) / clear(m) | Zeroes elements / deletes all entries (Go 1.21) | No | Does not change len(s) |
slices.Clone(s) | Independent copy, cap == len | Yes | Shallow: pointers inside are shared |
slices.Delete(s, i, j) | Removes s[i:j], zeroes the tail (Go 1.22) | No | Old views see zeros |
make(map[K]V, hint) | Preallocates for about hint entries | Yes | Not a size limit |
v, ok := m[k] | Comma-ok: tells missing from zero | No | m[k] alone returns zero for missing |
maps.Keys(m) | Iterator over keys (Go 1.23) | No | Order unspecified; wrap in slices.Sorted |
The bugs that reach production.
| Bug | Symptom | Root cause | Fix |
|---|---|---|---|
| Append to a sub-slice | Another slice's data changes | Shared backing array, spare capacity | s[a:b:b] or slices.Clone |
| "Sometimes it changes, sometimes not" | Flaky test | append shares only when len < cap | Never rely on either; always use the result |
| Retained buffer | RSS grows; heap profile shows ReadFile | 6-byte sub-slice keeps 64 MiB array | bytes.Clone, strings.Clone |
| Write to nil map | panic: assignment to entry in nil map | var m map[K]V never maked | make in the constructor |
| Concurrent writes | fatal error: concurrent map writes (not recoverable) | Map used from two goroutines | Mutex, or sync.Map |
| Ordered output expected | Flaky JSON/golden tests | Map order is unspecified and randomised | slices.Sorted(maps.Keys(m)) |
API returns null | JS client: Cannot read properties of null | nil slice marshals to null | Initialise to []T{} |
| Loop over index then append | index out of range [3] with length 3 | Using make([]T, n) then append | make([]T, 0, n) |
Why it exists
Memory is a row of bytes. A program needs three things on top of it: a fixed group of values that behaves like one value (a colour, a SHA-256 digest, a 3×3 board), a sequence whose length changes at run time (rows from a query, lines of a file), and lookup by key (sessions by ID, prices by SKU). C gives you only the first and pointers; PHP gives you one "array" that is all three at once. Go separates them so the cost of each operation is visible: an array is a value and is copied; a slice is a cheap header that refers to an array, so passing it is O(1) but sharing is implicit; a map is a reference to a runtime hash table that grows by itself and promises nothing about order or concurrency.
| Simple and explicit | Convenient and implicit |
|---|---|
| Array: size fixed at compile time, copied on assignment | Slice: size changes, header copied, elements shared |
| No allocation surprises; can live on the stack | append may allocate and move data behind your back |
| Comparable, usable as a map key | Not comparable; need slices.Equal |
| Map with a mutex you own | sync.Map that hides the locking but loses type safety (any) |
| Sort the keys when you need order | An ordered hash map (PHP) that always pays for order |
The analogy we reuse on this page: a warehouse. The backing array is a numbered run of shelves bolted to the floor; it never moves and never grows. A slice is a pick-list card that says "start at shelf 12, you own 4 items, and the run has 10 shelves left from shelf 12". Two cards can point at the same shelves; if one picker places a box on shelf 16 (an append inside the remaining capacity), the other picker's card, which also covers shelf 16, now sees that box. When a card needs more shelves than the run has left, the warehouse rents a bigger run elsewhere, moves the boxes there and writes a new card (growslice); old cards still point at the old shelves. A map is the coat-check counter: you hand in a ticket (key) and get a coat (value); the attendant decides where coats hang, re-hangs them when the room gets full, and two attendants grabbing the same hook at once is a fight the manager stops by closing the counter (fatal error).
Three common misunderstandings, up front
- "Slices are passed by reference." Everything in Go is passed by value. A slice argument copies the 24-byte header; the callee can change the elements you see, but if it appends and grows, its new length and new array are invisible to you unless it returns the slice. That is why
appendreturns a value. - "
appendalways copies" or "appendnever copies". Both are wrong. It writes into the existing array whenlen(s)+n <= cap(s)and allocates a new one otherwise. Code that is correct only in one of those cases is a bug waiting for a different input size. - "Maps are ordered, just random-looking." The specification says the iteration order "is not specified and is not guaranteed to be the same from one iteration to the next", and the runtime deliberately randomises it. Sort the keys if order matters.
Where it comes from
The array/slice/map split is in Go 1.0 (March 2012) and has not changed since; what changed is the library around it and the runtime underneath. Andrew Gerrand's "Go Slices: usage and internals" (5 January 2011) introduced the slice header and the "possible gotcha" of re-slicing: "re-slicing a slice doesn't make a copy of the underlying array". Rob Pike's "Arrays, slices (and strings): The mechanics of 'append'" (26 September 2013) explains why append must return a slice. Gerrand's "Go maps in action" (6 February 2013) states the rule that every Go programmer later relearns the hard way: "Maps are not safe for concurrent use". Effective Go puts the array rule in one line: "Arrays are values. Assigning one array to another copies all the elements."
| Version | Change (from the release notes read for this page) |
|---|---|
| Go 1.0 (2012) | Arrays, slices, maps, make, append, copy, delete, range |
| Go 1.2 (2013) | "Three-index slices": s[low:high:max] sets the capacity |
| Go 1.12 (2019) | fmt prints maps "in key-sorted order to ease testing" (printing only; iteration stays random) |
| Go 1.17 / 1.20 | Slice → array pointer conversion (1.17), slice → array conversion [4]byte(s) (1.20) |
| Go 1.21 (2023) | Packages slices and maps (generic), built-ins clear, min, max |
| Go 1.22 (2024) | slices.Concat; Delete, DeleteFunc, Compact, CompactFunc, Replace "now zero the elements between the new length and the old length"; per-iteration loop variables; range over integers |
| Go 1.23 (2024) | Range-over-func iterators; slices.All, Values, Backward, Collect, AppendSeq, Sorted, Chunk; maps.All, Keys, Values, Insert, Collect |
| Go 1.24 (2025) | New built-in map "based on Swiss Tables" (opt out with GOEXPERIMENT=noswissmap); new sync.Map implementation (GOEXPERIMENT=nosynchashtriemap) |
| Go 1.25 / 1.26 | The compiler can allocate slice backing stores "on the stack in more situations" |
The growth formula in today's runtime (nextslicecap in runtime/slice.go) dates from Go 1.18, whose release notes say append "now uses a slightly different formula" that "is less prone to sudden transitions in allocation behavior" (earlier releases switched abruptly from 2x to 1.25x at 1024 elements). The Swiss table design comes from Google's Abseil C++ library; Michael Pratt's post "Faster Go maps with Swiss Tables" (26 February 2025) explains how Go adapted it: "In microbenchmarks, map operations are up to 60% faster than in Go 1.23."
The concept catalogue
Every block follows the same order: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, per-version or per-variant behaviour, and the fix in Go (full tested code in Solving the classic problems).
Arrays are values Must-know
In plain words: an array is a fixed number of elements stored side by side. [3]uint8 and [4]uint8 are different types. Assigning or passing an array copies every element, exactly like assigning an int.
Common misunderstanding: "Arrays are like slices but faster." They are a different kind of thing: a value, not a view. A function that receives [1 << 20]byte copies a megabyte on every call; a function that modifies its array parameter modifies a copy. Another one: "arrays are useless in Go." They are the right type for fixed-size data: sha256.Sum256 returns [32]byte, which you can compare with == and use as a map key.
Definition: spec: "The length is part of the array's type; it must evaluate to a non-negative constant representable by a value of type int." Arrays are comparable when their element type is, element by element. [...]T{...} lets the compiler count the length. An array literal or a local array that does not escape lives on the stack. Since Go 1.20, [N]T(s) converts a slice to an array by copying, and panics when len(s) < N.
1 var a [3]int // [0 0 0], usable immediately, no make
2 b := a // copies 3 ints
3 b[0] = 7 // a is still [0 0 0]
4 f(a) // f receives its own copy
5 p := &a; p[1] = 9 // a pointer to an array indexes the original: a == [0 9 0]
6 a == [3]int{0, 9, 0} // true: element-wise comparisonReal scenario: deduplicating webhook deliveries by sha256.Sum256(body) in a map[[32]byte]struct{}; a tic-tac-toe or seat-map board [3][3]byte copied for "what if" search without aliasing; IPv4 addresses as [4]byte (netip.Addr.As4 returns one); a bug where a 64 KiB [65536]byte buffer is a struct field and the struct is passed by value through five layers.
| Situation | Array [N]T | Slice []T |
|---|---|---|
| Size known at compile time | Natural fit | Works, but carries a header |
| Pass to a function | Copies N elements | Copies 24 bytes |
== and map key | Allowed (if T comparable) | Compile error |
| Grow | Impossible | append |
Sort with slices.Sort | slices.Sort(a[:]) | slices.Sort(s) |
Fix / how to use it: use arrays for fixed-size identity values (digests, coordinates, small boards); pass *[N]T or a[:] when the array is large; never put a huge array in a struct that is passed by value. Tested code: arrays.
The slice header: pointer, length, capacity Must-know
In plain words: a slice is three words: a pointer to the first element it can see, its length (how many elements you can index) and its capacity (how many elements exist from that pointer to the end of the backing array).
Common misunderstanding: "len and cap are the same unless I use make with three arguments." Every slice expression changes them independently: s[2:4] on a slice of capacity 8 has length 2 and capacity 6. Another: "a slice owns its elements." It owns nothing; the backing array is owned by whoever holds any pointer into it, and the garbage collector keeps it alive as long as any slice does.
Definition: in the runtime the header is struct { array unsafe.Pointer; len int; cap int } (24 bytes on 64-bit). Spec: capacity "is the sum of the length of the slice and the length of the array beyond the slice". Indexing s[i] is checked against len; slicing s[a:b] is checked against cap, which is why you can re-extend a slice up to its capacity (s[:cap(s)]). A string header is the same minus cap.
1 a := make([]int, 8) // header {ptr=&arr[0], len=8, cap=8}
2 t := a[2:4] // header {ptr=&arr[2], len=2, cap=6}
3 t[0] = 5 // a[2] == 5: same array
4 t = t[:cap(t)] // len 6: t now sees a[2:8]
5 _ = t[6] // panic: index out of range [6] with length 6
6 _ = t[:7] // panic: slice bounds out of range [:7] with capacity 6Real scenario: paginating a result set by sub-slicing (rows[offset:offset+limit]) and then appending a summary row; a bufio reader returning a slice into its internal buffer that is overwritten on the next read (bufio.Reader.ReadSlice documents this); passing a slice to a worker goroutine that keeps it after the producer reused the buffer.
| Expression | len | cap | Shares array with a? |
|---|---|---|---|
a[i:j] | j-i | cap(a)-i | Yes |
a[i:j:k] | j-i | k-i | Yes |
a[:0] | 0 | cap(a) | Yes |
a[len(a):] | 0 | cap(a)-len(a) | Yes (the spare room) |
slices.Clone(a) | len(a) | len(a) (rounded) | No |
append(a[:0:0], a...) | len(a) | ≥ len(a) | No (old idiom for Clone) |
Fix / how to use it: always reason about all three fields; return clipped or cloned slices from APIs; document when a returned slice is a view ("valid until the next call"). See the diagram above and after.Page.
make, literals and the zero value Must-know
In plain words: make builds a slice, map or channel ready to use. For slices you choose the length and optionally the capacity; for maps you give an optional size hint. A literal ([]int{1, 2}, map[string]int{"a": 1}) builds and fills in one step.
Common misunderstanding: "make([]T, n) reserves room for n items." It creates n zero items. Then append adds item n+1. The classic result is a slice with n zeros followed by your data. Another: "a nil slice must be maked before append." append on a nil slice works; only maps need make before writing.
Definition: make([]T, len, cap) allocates a hidden array of cap elements, all zero, and returns a header with that len and cap; it panics with makeslice: len out of range or makeslice: cap out of range on bad values. make(map[K]V, hint): spec "The initial capacity does not bound its size: maps grow to accommodate the number of items stored in them, with the exception of nil maps." new([]T) returns a pointer to a nil slice and is almost never what you want.
1 s := make([]string, 3) // ["" "" ""], len 3 cap 3
2 s = append(s, "a") // ["" "" "" "a"] <- the classic bug
3 t := make([]string, 0, 3) // [], len 0 cap 3
4 t = append(t, "a") // ["a"], no allocation
5 var m map[string]int // nil map
6 _ = m["x"] // 0, reading is fine
7 m["x"] = 1 // panic: assignment to entry in nil mapReal scenario: converting 10 000 database rows to DTOs with make([]DTO, len(rows)) and then append: the API returns 20 000 items, half empty; a struct with a map field created with &Cache{} instead of a constructor panics on the first Set; make([]byte, n) with n read from an untrusted length prefix lets one request allocate gigabytes.
| Form | len | cap | Ready for append | Ready for s[i] = |
|---|---|---|---|---|
var s []T | 0 | 0 | Yes | No |
s := []T{} | 0 | 0 | Yes | No |
make([]T, n) | n | n | Yes (after the zeros) | Yes, i < n |
make([]T, 0, n) | 0 | n | Yes, no realloc until n | No |
make([]T, n, m) | n | m | Yes | Yes, i < n |
Fix / how to use it: make([]T, 0, n) + append when you build; make([]T, n) + index assignment when you fill positions; constructors that make every map field; validate sizes from input before make. Code: prealloc.
append and the growth factor Must-know
In plain words: append puts elements after the last one. If the backing array has room, it writes there. If not, the runtime allocates a bigger array, copies the old elements, adds the new ones and returns a header pointing to the new array.
Common misunderstanding: "Capacity always doubles." It doubles only while the old capacity is below 256 elements; after that each step adds a quarter plus 192 elements, so the factor slides from about 2x down towards 1.25x. And the result is then rounded up to a memory size class, so the numbers you see are not exactly the formula. Another: "the growth is in elements." The rounding is in bytes, so a []byte and a []int64 grow through different capacities.
Definition: spec: "If the capacity of s is not large enough to fit the additional values, append allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise, append re-uses the underlying array." The runtime's nextslicecap(newLen, oldCap) (Go 1.27.4 source):
// from runtime/slice.go, nextslicecap
if newLen > doublecap { return newLen }
const threshold = 256
if oldCap < threshold { return doublecap }
for {
// Transition from growing 2x for small slices
// to growing 1.25x for large slices.
newcap += (newcap + 3*threshold) >> 2
if uint(newcap) >= uint(newLen) { break }
}growslice then calls roundupsize so the allocation fills a malloc size class, recomputes the capacity from the rounded byte count, allocates, and memmoves the old elements.
appends to a local []int64, Go 1.27.4 darwin/arm64 (lab experiment 1)
1 cap 0 -> 4 first append: a 32-byte stack buffer (compiler, Go 1.25+)
2 cap 4 -> 8 -> 16 -> 32 -> 64 -> 128 -> 256 -> 512 doubling below 256
3 cap 512 -> 848 formula 512+(512+768)/4 = 832, 6656 B rounded to size class 6784 B
4 cap 848 -> 1280 formula 1252, rounded up
5 cap 1280 -> 1792 -> 2560 ... factor ~1.4, then towards 1.25 for large slicesReal scenario: a CSV import that appends 5 million rows one by one: about 48 reallocations by the formula and roughly 2x peak memory during each copy; a hot path that builds a 10-element slice per request: with make(…, 0, 10) one allocation, without it several; a test that asserts cap(s) == 8 and breaks on a Go upgrade or another architecture.
| Old cap | Factor from nextslicecap (before rounding) |
|---|---|
| < 256 | 2.0 |
| 256 | 2.0 (256 + 256 = 512) |
| 512 | 1.625 |
| 1024 | 1.44 |
| 4096 | 1.30 |
| ≥ 100 000 | ≈ 1.25 |
Fix / how to use it: always assign the result (s = append(s, x)); preallocate when the final size is known or bounded (make, slices.Grow); never test exact capacities beyond "at least". Tested reproduction of the formula: growth.
Aliasing and the shared backing array Must-know
In plain words: two slices alias when they point into the same array. A write through one is visible through the other, and an append through one can overwrite elements the other one considers its own.
Common misunderstanding: "I appended to my slice, so I only changed my data." If your slice was cut from a bigger one and has spare capacity, the "free" room is someone else's elements. Another: "aliasing is only a problem with goroutines." The most common aliasing bugs are single-threaded.
Definition: spec: "A slice therefore shares storage with its array and with other slices of the same array; by contrast, distinct arrays always represent distinct storage." Two appends to the same base with spare capacity write to the same slot; the second wins. After a reallocating append, the slices no longer alias, which is why aliasing bugs look intermittent.
base := make([]int, 3, 4) lab experiment 2 (real output)
1 a := append(base, 1) fits: writes arr[3] = 1, a shares base's array
2 b := append(base, 2) fits: writes arr[3] = 2, overwrites a[3]
3 fmt.Println(a, b) a: [0 0 0 2] b: [0 0 0 2] same array: true
4 c := append(a, 3) a is full (len 4 cap 4): new array
5 c[0] = 100 a: [0 0 0 2] c: [100 0 0 2 3]Real scenario: a pagination helper returns events[0:20], a renderer appends a "load more" marker, and event 21 disappears from the next page; a recursive permutation/backtracking function appends path to results without copying and every result ends up identical; a middleware stores r.Header["X-Tags"] and another appends to it; a worker gets batch := buf[:n], the producer reuses buf and the worker processes the next batch's data.
| Pattern | Aliases? | Safe when |
|---|---|---|
t := s[a:b] then write t[i] | Yes | You intend to share |
t := s[a:b] then append(t, x) | Yes, if b < cap(s) | s[b:] is unused |
t := s[a:b:b] then append(t, x) | No (append reallocates) | Always |
t := slices.Clone(s[a:b]) | No | Always (costs a copy) |
results = append(results, path) in recursion | Yes | Never: clone path |
Fix / how to use it: treat any slice you received as possibly shared; cut results with a full slice expression or clone them; in recursion, append(results, slices.Clone(path)). Code: before/after.
Full slice expression s[low:high:max] Important
In plain words: the three-index slice lets you cut a slice and limit how far it can see. With capacity equal to length, the first append must allocate, so it can never write into the caller's array.
Common misunderstanding: "s[a:b:b] copies the elements." It copies nothing; reads and writes through the result still hit the original array. It only protects against append spilling over. Another: "it works on strings." Spec: "For an array, pointer to array, or slice a (but not a string)".
Definition: a[low : high : max] has length high-low and capacity max-low. "The indices are in range if 0 <= low <= high <= max <= cap(a), otherwise they are out of range." Only the first index may be omitted. slices.Clip(s) is s[:len(s):len(s)].
1 events := []Event{e1, e2, e3, e4} // len 4 cap 4
2 p := events[0:2:2] // len 2 cap 2
3 p = append(p, marker) // cap exceeded: new array of cap 4
4 events[2] == e3 // true: caller's data intact
5 p[0].Action = "x" BEFORE step 3 // would change events[0]: still shared for writesReal scenario: library functions returning sub-slices of an internal buffer (bytes.Fields style); splitting a batch into chunks for parallel workers so a worker's append cannot touch its neighbour's chunk; building row slices out of one contiguous matrix buffer (matrix.Contiguous).
| Tool | Protects against append spill | Protects against writes | Copies |
|---|---|---|---|
s[a:b] | No | No | No |
s[a:b:b] / slices.Clip | Yes | No | No |
slices.Clone(s[a:b]) | Yes | Yes | Yes |
Fix / how to use it: return s[a:b:b] from APIs that hand out views; return slices.Clone when the caller may keep the data or write to it.
copy semantics Important
In plain words: copy(dst, src) copies elements from one slice to another, as many as fit, and returns that number. It never allocates and never grows dst.
Common misunderstanding: "copy into an empty slice makes a copy." var dst []int; copy(dst, src) copies zero elements, because len(dst) is 0. Another: "overlapping copies are undefined." copy is defined for overlapping slices; it behaves like memmove.
Definition: spec: "The number of elements copied is the minimum of len(src) and len(dst)." A special case copies bytes from a string: copy(b, "Hello"). Example from the spec: n2 := copy(s, s[2:]) // n2 == 4, s is []int{2, 3, 4, 5, 4, 5}.
1 dst := make([]int, 2)
2 n := copy(dst, []int{7, 8, 9}) // n == 2, dst == [7 8]
3 var empty []int
4 copy(empty, []int{1}) // 0: nothing copied
5 s := []int{1, 2, 3, 4, 5}
6 copy(s, s[2:]) // s == [3 4 5 4 5], returns 3: shift leftReal scenario: shifting a ring buffer left; copying a request body prefix into a fixed header buffer; the deletion idiom s = s[:i+copy(s[i:], s[i+1:])] from SliceTricks (now slices.Delete).
| Need | Use |
|---|---|
| Independent copy of a slice | slices.Clone(s) |
| Copy into an existing buffer | copy(buf, s) and check the count |
| String to fresh bytes | []byte(s) |
| Append one slice to another | append(dst, src...) |
Fix / how to use it: size dst with make([]T, len(src)) before copy, or use slices.Clone. Code: aliasing.ShiftLeft.
Reuse with s[:0] and in-place filtering Important
In plain words: s[:0] is an empty slice that keeps the whole capacity. Appending to it refills the same array: no allocation. It is how you filter in place and how you reuse a buffer across loop iterations.
Common misunderstanding: "s[:0] frees the memory" (it keeps all of it) or "after filtering, the old slice is still valid" (it now shows the filtered prefix and leftover tail). Another: "reusing a buffer is always safe." Anything that kept a view of the previous contents now sees the new contents.
Definition: out := s[:0]; for _, v := range s { if keep(v) { out = append(out, v) } } writes each kept element at or before its original index, so it never overwrites an element not yet read. Elements past len(out) remain; zero them with clear(s[len(out):]) when they hold pointers. slices.DeleteFunc does exactly this and zeroes the tail (Go 1.22).
1 s := []int{3, -1, 4, -1, 5}
2 out := s[:0] // len 0, cap 5, same array
3 keep 3 -> s[0]=3; skip; keep 4 -> s[1]=4; skip; keep 5 -> s[2]=5
4 clear(s[3:]) // s == [3 4 5 0 0], out == [3 4 5]
5 batch := buf[:0] each iteration // zero allocations after the first fillReal scenario: dropping expired sessions from a slice every minute; a log shipper that collects 500 lines, flushes, and reuses the buffer; a parser that reuses a token slice per line. The bug version: the flush function hands the batch to a goroutine that sends it later, while the loop already overwrites it.
| Approach | Allocations | Old view after | Use when |
|---|---|---|---|
out := s[:0] + append | 0 | Shows filtered prefix | You own s |
slices.DeleteFunc(s, f) | 0 | Tail zeroed | Same, shorter |
| New slice + append | 1+ | Unchanged | s is shared |
buf = buf[:0] reuse | 0 per round | Overwritten next round | Consumer copies or finishes first |
Fix / how to use it: filter in place only slices you own; clear the tail; flush functions that keep data must slices.Clone. Code: aliasing.KeepPositive, Batcher.
Memory leaks through sub-slices Important
In plain words: a small slice pointing into a big array keeps the whole array alive. The garbage collector frees arrays, not parts of arrays.
Common misunderstanding: "Go has a GC, so it cannot leak." It cannot free what is still reachable, and a 6-byte header slice makes a 64 MiB file buffer reachable. The Go blog's "possible gotcha": "as long as the slice is kept around the garbage collector can't release the array". The same applies to strings: s[:10] of a 1 MiB string keeps the megabyte.
Definition: reachability is per allocation. A sub-slice (or substring) holds a pointer into the allocation; while any such pointer is live, nothing in that allocation is freed. Shrinking a []*T without zeroing the tail also keeps the dropped *T objects alive through the array.
1 data, _ := os.ReadFile("dump.log") // 64 MiB array
2 line := data[:bytes.IndexByte(data,'\n')] // 80-byte view, cap 64 MiB
3 cache[key] = line // the cache now pins 64 MiB per entry
4 fix: cache[key] = bytes.Clone(line) // 80-byte array; the 64 MiB is collectable
5 sessions = sessions[1:] // sessions[0]'s *Session still referenced by arr[0]Real scenario: an in-memory cache of the first line of uploaded files; a regex FindSubmatch result stored for later; a queue implemented as q = q[1:] that never releases the front pointers; substrings of big JSON documents kept as map keys.
| Leak | Detect | Fix |
|---|---|---|
| Sub-slice of big buffer | pprof heap: big allocation sites still live | bytes.Clone, slices.Clone |
| Substring of big string | Same | strings.Clone (Go 1.18) |
[]*T shrunk without zeroing | Objects survive GC | clear(tail), slices.Delete (1.22+) |
q = q[1:] queue | Array never shrinks | Ring buffer or periodic slices.Clone |
| Map that grew then emptied | Memory stays high | Make a new map (see Map internals) |
Fix / how to use it: clone anything you store long-term that was cut from a large buffer. Code: leak.
nil slice vs empty slice Must-know
In plain words: var s []int is nil; s := []int{} is empty but not nil. Both have length 0 and capacity 0, both work with len, range and append. They differ when compared to nil, under reflect, and in JSON.
Common misunderstanding: "nil slices are dangerous like nil pointers." Reading len, ranging and appending are all safe. The real difference is encoding/json: nil marshals to null, empty to []. Go's code-review guide: "a nil slice encodes to null, while []string{} encodes to the JSON array []".
Definition: spec: "The value of an uninitialized slice is nil." The CodeReviewComments wiki prefers var t []string and adds: "When designing interfaces, avoid making a distinction between a nil slice and a non-nil, zero-length slice". encoding/json documents that "a nil slice encodes as the null JSON value"; a nil map also encodes as null. slices.Equal(nil, []int{}) is true.
1 var a []string // a == nil, len 0
2 b := []string{} // b != nil, len 0
3 json.Marshal(a) // null
4 json.Marshal(b) // []
5 json.Unmarshal([]byte("[]"), &a) // a is now empty, NOT nil
6 json.Unmarshal([]byte("null"), &b) // b is now nilReal scenario: a TypeScript client doing response.orders.length crashes on null; an OpenAPI contract says type: array and a validator rejects null; a PHP client's count(null) throws a TypeError in PHP 8; a test compares with reflect.DeepEqual(got, []T{}) and fails for a nil result.
| Operation | nil slice | empty slice |
|---|---|---|
len, cap | 0, 0 | 0, 0 |
range, append | Works | Works |
s == nil | true | false |
json.Marshal | null | [] |
reflect.DeepEqual(s, []T{}) | false | true |
slices.Equal(s, []T{}) | true | true |
Fix / how to use it: inside Go code, return nil and test with len(s) == 0; at the JSON boundary, normalise to []T{} (and map[K]V{}). Code: nilempty.
The slices package Must-know
In plain words: slices (standard library since Go 1.21) is a set of generic functions for any slice type: search, sort, insert, delete, compare, clone. It replaces most hand-written loops and the x/exp/slices module.
Common misunderstanding: "slices functions return new slices." Most modify in place and return the possibly-shortened header (Delete, Compact, Insert may reallocate); you must use the result. Another: "Compact removes all duplicates." It removes consecutive duplicates; sort first.
Definition (Go 1.27.4 go doc): the functions you will use most:
| Function | Since | What it does | Note |
|---|---|---|---|
Sort, SortFunc | 1.21 | pdqsort, in place | "not guaranteed to be stable" |
SortStableFunc | 1.21 | Stable sort | Keeps order of equal elements |
IsSorted, IsSortedFunc | 1.21 | Check order | |
BinarySearch, BinarySearchFunc | 1.21 | (index, found) on a sorted slice | O(log n); returns insertion point |
Contains, Index, IndexFunc, ContainsFunc | 1.21 | Linear search | O(n) |
Equal, EqualFunc, Compare | 1.21 | Element-wise compare | nil equals empty |
Compact, CompactFunc | 1.21 | Remove consecutive duplicates | Zeroes tail since 1.22 |
Clone | 1.21 | Shallow copy | Preserves nilness |
Grow | 1.21 | Ensure room for n more | "at least n elements can be appended" |
Clip | 1.21 | s[:len(s):len(s)] | |
Delete, DeleteFunc | 1.21 | Remove s[i:j] / matching | "Delete zeroes the elements s[len(s)-(j-i):len(s)]" (1.22) |
Insert | 1.21 | Insert values at index | May reallocate |
Replace | 1.21 | Replace s[i:j] | Zeroes tail since 1.22 |
Reverse | 1.21 | In place | |
Min, Max, MinFunc, MaxFunc | 1.21 | Panics on empty slice | |
Concat | 1.22 | One allocation for all parts | |
Repeat | 1.23 | Repeat a slice n times |
1 tags := []string{"Go ", "sql", "go"}
2 out := slices.Clone(tags) // do not sort the caller's slice
3 lower-case each; slices.Sort(out) // [go go sql]
4 out = slices.Compact(out) // [go sql] (adjacent duplicates only)
5 slices.BinarySearch(out, "go") // 0, true
6 out = slices.Insert(out, 1, "pg") // [go pg sql]Real scenario: normalising user-entered tags; keeping a sorted list of permissions and checking membership with BinarySearch; removing a cancelled item from a cart with DeleteFunc; merging paginated API responses with Concat.
Fix / how to use it: prefer slices over hand loops; always assign the result; clone before mutating input you do not own. Code: slicesdemo.
Iterators: slices.All, Values, Collect, Sorted Important
In plain words: since Go 1.23 a function can be ranged over. slices.Values(s) and maps.Keys(m) return such functions (iter.Seq), and slices.Collect or slices.Sorted turn them back into slices. This lets you write slices.Sorted(maps.Keys(m)) in one line.
Common misunderstanding: "iterators are lazy lists you can index." An iter.Seq[V] is just func(yield func(V) bool); you can range over it once per call, not index it, and every call re-runs the source. Another: "maps.Keys returns a slice." It did in x/exp/maps; the standard one returns an iterator.
Definition: iter.Seq[V] and iter.Seq2[K, V]. slices.All yields (index, value), slices.Values yields values, slices.Backward yields in reverse, slices.Collect(seq) builds a new slice, slices.AppendSeq(s, seq) appends, slices.Sorted(seq) collects and sorts, slices.Chunk(s, n) yields sub-slices of length n (views, not copies). Release notes, Go 1.23: "The 'range' clause in a 'for-range' loop now accepts iterator functions".
1 stock := map[string]int{"z": 1, "a": 2, "m": 3}
2 seq := maps.Keys(stock) // iter.Seq[string], nothing computed yet
3 keys := slices.Sorted(seq) // ranges, collects, sorts: [a m z]
4 for i, v := range slices.Backward(keys) { ... } // 2 z, 1 m, 0 a
5 for chunk := range slices.Chunk(ids, 100) { ... } // chunk aliases idsReal scenario: deterministic JSON or logs from a map; splitting 10 000 IDs into IN lists of 500 for a database query (architecture); building a filtered slice from a map without an intermediate slice.
| Want | Before 1.23 | Go 1.23+ |
|---|---|---|
| Sorted map keys | loop + append + sort.Strings | slices.Sorted(maps.Keys(m)) |
| Values of a map | loop + append | slices.Collect(maps.Values(m)) |
| Batches of n | index arithmetic | slices.Chunk(s, n) |
| Reverse loop | for i := len(s)-1; i >= 0; i-- | range slices.Backward(s) |
Fix / how to use it: use iterators at the edges (sorting keys, collecting) and plain range inside hot loops; remember Chunk returns views. Code: slicesdemo.SKUs.
Sorting: sort vs slices.Sort, stable sort Important
In plain words: slices.Sort and slices.SortFunc are the modern, generic, faster sorts. Neither keeps the original order of equal elements. When that order matters, use slices.SortStableFunc (or sort.SliceStable), or add a tie-breaker to the comparison.
Common misunderstanding: "Sorting by priority keeps arrival order within a priority." Only a stable sort does. With pdqsort, equal elements can come out in any order, and the order can change with input size. Another: "sort.Slice is deprecated." It is not deprecated, but its docs point to slices.SortFunc as faster and more ergonomic.
Definition: slices.Sort sorts cmp.Ordered elements with pdqsort; SortFunc takes cmp func(a, b E) int (negative, zero, positive), "This sort is not guaranteed to be stable." SortStableFunc "sorts the slice x while keeping the original order of equal elements". sort.Sort/sort.Slice use an interface or a less(i, j) closure; sort.Stable/sort.SliceStable are stable. NaN: slices.Sort: "When sorting floating-point numbers, NaNs are ordered before other values."
tickets arrive in ID order, sorted by Priority only
1 input: (1,p2) (2,p1) (3,p2) (4,p1)
2 SortStableFunc: (2,p1) (4,p1) (1,p2) (3,p2) arrival order kept
3 SortFunc: (4,p1) (2,p1) (3,p2) (1,p2) allowed: equal elements may swap
4 SortFunc + cmp.Or(priority, id): always (2,p1) (4,p1) (1,p2) (3,p2)Real scenario: support tickets "first come, first served within a priority"; a leaderboard with ties that must not flicker between requests; a paginated endpoint sorted by a non-unique column (the same problem as SQL ORDER BY created_at without a unique tie-breaker).
| API | Generic | Stable | Comparison |
|---|---|---|---|
slices.Sort | Yes | No | < on cmp.Ordered |
slices.SortFunc | Yes | No | func(a, b E) int |
slices.SortStableFunc | Yes | Yes | func(a, b E) int |
sort.Slice | No (any) | No | less(i, j int) bool |
sort.SliceStable | No | Yes | less(i, j int) bool |
sort.Sort / sort.Stable | No (interface) | No / Yes | Len, Less, Swap |
Fix / how to use it: default to slices.SortFunc with cmp.Compare and cmp.Or tie-breakers; use SortStableFunc when input order carries meaning. Code: sortstable.
Strings as byte slices and the bytes package Important
In plain words: a string is a read-only slice of bytes. Converting []byte(s) or string(b) copies, because one side is mutable and the other is not. The bytes package mirrors strings for []byte.
Common misunderstanding: "len(s) is the number of characters." It is the number of bytes: len("héllo") == 6. (Runes are in Strings, Runes.) Another: "every conversion is a copy." The compiler skips the copy in some cases, such as m[string(b)] lookups and for range []byte(s), but you cannot rely on it for stored values.
Definition: a string header is (ptr, len). append(b, s...) and copy(b, s) accept a string as source (spec special cases). bytes.Buffer is a growable byte slice with Write* and Read*; strings.Builder builds a string without the final copy. bytes.Clone, bytes.Cut, bytes.Fields, bytes.EqualFold, bytes.TrimSpace mirror strings.
1 s := "hello"
2 b := []byte(s) // copy 1: mutable bytes
3 b[0] = 'H' // s is still "hello"
4 t := string(b) // copy 2: "Hello"
5 b = append(b, " world"...) // append a string directly, no []byte(" world")Real scenario: parsing HTTP header lines from a bufio.Reader without allocating a string per line; building a CSV export with bytes.Buffer; hashing a request body (sha256.Sum256(b)) and comparing digests as arrays.
| Need | Use | Copies |
|---|---|---|
| Build a string | strings.Builder | Once, while growing |
| Build bytes, then write | bytes.Buffer | While growing |
| Edit characters | []byte(s) … string(b) | Twice |
| Keep a piece of a big string | strings.Clone(s[i:j]) | Once, small |
| Split/trim bytes | bytes.Cut, bytes.Fields, bytes.TrimSpace | No (views) |
Fix / how to use it: keep data as []byte while parsing and convert once at the end; clone small pieces you keep. Code: bytesdemo.
Multi-dimensional data Good to know
In plain words: Go has no built-in matrix. You use an array of arrays ([3][3]T, fixed and contiguous), a slice of slices ([][]T, flexible, each row allocated separately), or one flat slice indexed by r*cols + c.
Common misunderstanding: "make([][]int, 3) makes a 3×N matrix." It makes 3 nil rows; each must be maked. Another: "[][]T is contiguous like C." Rows are independent allocations, can have different lengths, and can alias if you cut them from one buffer carelessly.
Definition: spec: "Array types are always one-dimensional but may be composed to form multi-dimensional types." Effective Go and the Go blog describe two allocation strategies for 2-D slices: allocate each row, or "allocate a single array and point the individual slices into it".
1 grid := make([][]float64, rows) // rows nil slices
2 for i := range grid { grid[i] = make([]float64, cols) } // rows allocations
3 cells := make([]float64, rows*cols) // one allocation
4 grid[i] = cells[i*cols:(i+1)*cols:(i+1)*cols] // cap each row: no spill into the next
5 flat: cells[r*cols+c] // fastest for numeric loopsReal scenario: a seat map for a venue ([][]Seat, rows of different lengths); an image as a flat []uint8 with stride (that is what image.RGBA.Pix is); a pricing matrix loaded from a spreadsheet; a dynamic-programming table.
| Layout | Allocations | Jagged rows | Cache-friendly |
|---|---|---|---|
[R][C]T | 0–1 | No | Yes |
[][]T, row by row | R (+1) | Yes | Less |
[][]T over one buffer | 1 (+1) | No | Yes |
Flat []T + index | 1 | No | Yes |
Fix / how to use it: flat or single-buffer layouts for numeric work; jagged [][]T when rows differ. Measured in the lab: 100×100 jagged = 100 allocations, 12 µs; contiguous = 1 allocation, 4.6 µs. Code: matrix.
Maps: hash map basics, zero value, comma-ok Must-know
In plain words: a map stores key → value pairs and finds a value by key in (amortised) constant time. Reading a missing key returns the value type's zero value; the two-value form v, ok := m[k] tells you whether the key was there.
Common misunderstanding: "a missing key returns nil or an error." It returns the zero value: 0, "", false, a zero struct. That is a feature (counts[w]++ works without checking) and a trap (a price of 0 and a missing price look the same). Another: "a map variable holds the data." It holds a pointer to a runtime structure; copying the variable shares the entries.
Definition: spec: "A map is an unordered group of elements of one type, called the element type, indexed by a set of unique keys of another type, called the key type. The value of an uninitialized map is nil." len(m) is the number of entries; delete(m, k) is a no-op for missing keys and nil maps. A map[K]struct{} is the idiomatic set (empty struct values take no space).
1 prices := map[string]int{"free-sample": 0}
2 prices["missing"] // 0 (zero value)
3 p, ok := prices["free-sample"] // 0, true
4 p, ok = prices["missing"] // 0, false
5 counts[word]++ // read zero, add 1, store: no "if exists"
6 m2 := prices; m2["x"] = 1 // prices["x"] == 1 too: same tableReal scenario: feature flags where "missing" must mean "use default" and "false" means "explicitly off"; counting events per tenant; a set of seen message IDs for idempotency; a lookup of permission names to bits.
| Read form | Missing key | Present key |
|---|---|---|
v := m[k] | zero value | value |
v, ok := m[k] | zero value, false | value, true |
_, ok := m[k] | false | true (membership) |
| nil map read | zero value, false | — |
Fix / how to use it: use comma-ok whenever zero is a legal value; use map[K]struct{} for sets; make maps in constructors. Code: mapsdemo.
Map internals: buckets to Swiss tables Good to know
In plain words: a Go map is a hash table: the key is hashed, the hash picks where to look, and the runtime grows the table when it gets too full. Go 1.24 replaced the old bucket design with Swiss tables, which compare eight slots at once using a small fingerprint of the hash.
Common misunderstanding: "a map with 1 000 000 entries that I emptied with delete gives the memory back." Maps grow but never shrink; issue golang/go#20135 ("runtime: shrink map as elements are deleted") is still open, and the workaround from that thread is "to make a new map and copy in elements from the old". Another: "the load factor is a knob." It is a runtime constant.
Definition: Go 1.24+ (internal/runtime/maps): each map has a per-map random hash seed. The 64-bit hash splits into H1 ("Upper 57 bits") that selects the group and H2 ("Lower 7 bits") stored in the control word. A group is 8 slots plus an 8-byte control word; lookup compares H2 against all 8 control bytes in parallel, then checks the full key only for matches, and probes the next group until it finds one with an empty slot. A table grows when it passes a 7/8 load factor (maxAvgGroupLoad = 7 of MapGroupSlots = 8); a table holds at most 1024 slots (maxTableCapacity), beyond which it splits in two using extendible hashing over a directory, so "the upper bound for a single insertion is the latency of growing a 1024-entry table into two 1024-entry tables". Maps of at most 8 entries are a single group with no directory. Keys and values larger than 128 bytes are stored indirectly. Go 1.23 and earlier: arrays of buckets with 8 key/value pairs each, overflow buckets, growth when the average load reaches 6.5 per bucket ("about 80% full"), and incremental evacuation of old buckets.
m[k] lookup, Go 1.24+
1 h := hash(k, m.seed) // seed differs per map and per run
2 table := directory[h >> (64 - globalDepth)]
3 g := group at H1(h) mod groups // start of probe sequence
4 match := ctrl bytes == H2(h) // 8 comparisons in one word operation
5 for each match: compare full key // usually 0 or 1 candidates
6 no match and group has an empty slot -> key absent; else probe next groupReal scenario: an in-process cache that peaks at 5 million keys during a backfill and then stays at that memory forever; a latency-sensitive service where Go's incremental growth avoids a 1 GB rehash pause (the Swiss table post's motivating example); upgrading to Go 1.24 and seeing map-heavy benchmarks improve (the post: "up to 60% faster" in microbenchmarks, with "some edge cases" regressing).
| Aspect | Go ≤ 1.23 (buckets) | Go 1.24+ (Swiss tables) |
|---|---|---|
| Slot grouping | Bucket of 8 pairs + tophash bytes | Group of 8 slots + control word (H2) |
| Collisions | Overflow buckets (chaining) | Open addressing, probe sequence over groups |
| Max load | 6.5 per bucket (~81%) | 7/8 (87.5%) per table |
| Growth | Double, evacuate incrementally | Per table: double up to 1024, then split |
| Shrinks after delete | No | No |
| Iteration order | Randomised start | "explicitly randomized" |
| Opt-out | — | GOEXPERIMENT=noswissmap (Go 1.24) |
Fix / how to use it: make(map[K]V, hint) when you know the size (the runtime computes targetCapacity := (hint * 8) / 7); rebuild maps that shrank by orders of magnitude; never depend on any of the internals above.
Iteration order and range over maps Must-know
In plain words: for k, v := range m visits every entry once, in an order you cannot predict and that changes between runs and even between two loops in the same run.
Common misunderstanding: "fmt.Println(m) shows a stable order, so iteration is stable." Since Go 1.12 fmt sorts keys when printing; range does not. Another: "small maps iterate in insertion order." They may appear to by accident, then change.
Definition: spec: "The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next." The runtime randomises the starting point on purpose so programs cannot depend on it. maps.Keys/maps.All have the same rule ("The iteration order is not specified and is not guaranteed to be the same from one call to the next").
lab experiment 3, three loops over the same 5-key map (real output)
1 d e a b c
2 a b c d e
3 d e a b cReal scenario: a golden-file test that passes locally and fails in CI; an HMAC signature over query parameters built by ranging a map, so the signature differs between client and server; JSON produced by a hand-written encoder that ranges a map (note: encoding/json itself sorts map keys).
| Output | Ordered? |
|---|---|
for range m | No, randomised |
maps.Keys(m), maps.All(m) | No |
fmt.Print(m) (Go 1.12+) | Yes, sorted keys |
json.Marshal(m) | Yes, sorted keys |
slices.Sorted(maps.Keys(m)) | Yes |
Fix / how to use it: sort keys whenever output, signatures or tests depend on order; keep a separate []K if you need insertion order (that is what PHP arrays do for you). Code: mapsdemo.SortedKeys.
Mutating maps: delete during range, clear, not addressable Important
In plain words: you may delete entries while ranging over a map; you may add entries too, but they may or may not be visited. clear(m) empties a map. You cannot assign to a field of a struct stored in a map (m[k].Balance = 1), because map elements are not addressable.
Common misunderstanding: "deleting while iterating is undefined behaviour, like in Java or C++." Go defines it. Another: "m[k].f++ should work like a struct variable." The map may move entries during growth, so the language forbids taking their address.
Definition: spec: "If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped." clear(m) "deletes all entries, resulting in an empty map (len(m) == 0)" (Go 1.21); it keeps the allocated table. The compiler rejects m["a"].X = 1 with cannot assign to struct field m["a"].X in map and &m["a"] with cannot take address of m["a"].
1 for id, a := range accounts { if a.Balance == 0 { delete(accounts, id) } } // defined
2 accounts["acc-1"].Balance += 5 // compile error: cannot assign to struct field ... in map
3 a := accounts["acc-1"]; a.Balance += 5; accounts["acc-1"] = a // read-modify-write
4 ptrs["acc-1"].Balance += 5 // fine with map[string]*Account
5 clear(accounts) // len 0, memory kept for reuseReal scenario: evicting expired entries from a cache in one pass; updating counters stored in map[string]Stats; resetting a per-request scratch map with clear instead of reallocating it in a hot loop.
| Element type | m[k].f = v | In-place update | Cost |
|---|---|---|---|
map[K]T (struct) | Compile error | Read, modify, write back | Copies the struct twice |
map[K]*T | Allowed | Yes | One allocation per value, GC scanning |
map[K][]T | m[k][i] = v allowed | Elements yes, append needs write-back | Slice header in the map |
Fix / how to use it: read-modify-write for small structs; pointers for large or shared ones; clear to reuse. Code: mapsdemo.Deposit.
Map key types and NaN Good to know
In plain words: any type that supports == can be a key: numbers, strings, booleans, pointers, channels, arrays and structs of those, and interfaces. Slices, maps and functions cannot. Floating-point NaN is legal but never equals itself, so a NaN key can be inserted but never found.
Common misunderstanding: "map[any]V accepts anything." It accepts anything at compile time and panics at run time when the dynamic key is a slice: panic: runtime error: hash of unhashable type []int. Another: "a struct key with a pointer field compares the pointees." It compares the pointer addresses.
Definition: spec: "The comparison operators == and != must be fully defined for operands of the key type; thus the key type must not be a function, map, or slice. If the key type is an interface type, these comparison operators must be defined for the dynamic key values; failure will cause a run-time panic." Because NaN != NaN, each m[NaN] = v adds a new entry; lookups and delete never match it; only clear removes such entries (one of the reasons clear was added in Go 1.21). -0.0 == +0.0, so they are the same key.
1 m := map[float64]string{}
2 m[math.NaN()] = "a"; m[math.NaN()] = "b"
3 len(m) // 2
4 _, ok := m[math.NaN()] // false
5 clear(m); len(m) // 0Real scenario: composite keys struct{ TenantID, SKU string } instead of string concatenation (tenant+":"+sku breaks when an ID contains a colon); [32]byte digest keys; a metrics aggregator keyed by float64 latency buckets that silently accumulates NaN entries from a division by zero.
| Key type | Allowed | Note |
|---|---|---|
string, ints, bool | Yes | Most common |
float64 | Yes | NaN never found; -0 == +0 |
[N]T array, struct of comparable fields | Yes | Composite keys without concatenation |
| Pointer, channel | Yes | Identity, not content |
Interface (any) | Yes | Panics if dynamic type is not comparable |
| Slice, map, func | No | invalid map key type []int |
Fix / how to use it: struct or array keys for composite identity; reject NaN before using floats as keys; avoid map[any]V with untrusted dynamic types. Code: mapsdemo.NaNKeys, arrays.Visited.
Maps and goroutines: concurrent map writes, mutex, sync.Map Must-know
In plain words: a map is safe for many goroutines that only read. As soon as one goroutine writes while another reads or writes, you need a lock. Without one, the runtime may detect it and kill the process with fatal error: concurrent map writes, which recover cannot catch.
Common misunderstanding: "it is just a data race, the worst case is a wrong value." For maps the runtime's check aborts the whole program, taking every in-flight request with it. Another: "use sync.Map for every shared map." The docs say it "is optimized for two common use cases"; for everything else a plain map with a mutex is simpler, typed and often faster.
Definition: Go FAQ, "Why are map operations not defined to be atomic?": "requiring that all map operations grab a mutex would slow down most programs and add safety to few", and "Map access is unsafe only when updates are occurring." The runtime reports fatal error: concurrent map writes, fatal error: concurrent map read and map write or concurrent map iteration and map write when it notices. go test -race reports WARNING: DATA RACE with both stacks. sync.Map is for "(1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys". Go 1.24 shipped a new implementation (opt out with GOEXPERIMENT=nosynchashtriemap).
T1 (handler A) T2 (handler B) no lock
1 m["tenant-1"]++
2 m["tenant-2"]++ runtime detects
3 fatal error: concurrent map writes (whole process exits, exit status 2)
with c.mu.Lock()/Unlock() around both writes: serialised, correctReal scenario: a per-tenant rate-limit counter in a package-level map; a lazily filled config cache written by the first request of each tenant; a WebSocket hub's map of connections modified on join/leave while a broadcaster ranges over it.
| Option | Typed | Good for | Cost |
|---|---|---|---|
map + sync.Mutex | Yes | General read/write | All access serialised |
map + sync.RWMutex | Yes | Read-heavy, short critical sections | RLock overhead under write contention |
sync.Map | No (any) | Write-once caches, disjoint keys | Type assertions; no len |
| Sharded maps (N × mutex+map) | Yes | Very hot counters | More code |
| One owner goroutine + channels | Yes | Complex invariants | Latency per operation |
Fix / how to use it: wrap the map and its mutex in a struct, pass a pointer (go vet reports passes lock by value otherwise), copy before ranging outside the lock; reach for sync.Map only for its two cases. Details of mutexes are in sync & atomic. Code: safemap.
The maps package Important
In plain words: maps (Go 1.21, iterators in 1.23) gives you generic helpers: copy a map, compare two maps, iterate keys or values, and build a map from an iterator.
Common misunderstanding: "maps.Clone is a deep copy." It is shallow: pointer, slice and map values are shared between the original and the clone. Another: "maps.Keys gives me a sorted slice." It gives an unordered iterator.
Definition: Clone(m) (shallow, preserves nil), Copy(dst, src) (overwrites keys in dst), Equal, EqualFunc, DeleteFunc; since 1.23: All (key-value iterator), Keys, Values, Insert(m, seq), Collect(seq).
1 snap := maps.Clone(stock) // new table, same values
2 maps.Equal(snap, stock) // true
3 maps.DeleteFunc(stock, func(k string, v int) bool { return v == 0 })
4 keys := slices.Sorted(maps.Keys(stock)) // deterministic
5 m2 := maps.Collect(maps.All(stock)) // same as Clone for a plain mapReal scenario: taking a snapshot of a config map under a lock and serving reads from the snapshot; comparing expected vs actual tag maps in a test; removing zero counters before writing metrics.
| Function | Since | Returns |
|---|---|---|
Clone, Copy | 1.21 | New map / nothing |
Equal, EqualFunc | 1.21 | bool |
DeleteFunc | 1.21 | nothing (in place) |
All, Keys, Values | 1.23 | iter.Seq2 / iter.Seq |
Insert, Collect | 1.23 | nothing / new map |
Fix / how to use it: clone under the lock, then work on the clone; deep-copy pointer values yourself when needed. Code: mapsdemo.
Comparing slices and maps Important
In plain words: arrays compare with ==. Slices and maps compare only with nil; for contents use slices.Equal and maps.Equal.
Common misunderstanding: "reflect.DeepEqual is the standard way." It works, but treats a nil slice and an empty slice as different, is slow, and compares unexported fields. Another: "bytes.Equal and slices.Equal differ." For []byte they agree, including nil vs empty.
Definition: spec: "Slice, map, and function types are not comparable. However, as a special case, a slice, map, or function value may be compared to the predeclared identifier nil." Compile error for a == b: invalid operation: a == b (slice can only be compared to nil). slices.Equal compares lengths then elements with == (so NaN elements are never equal); slices.EqualFunc takes a comparison function; slices.Compare gives a three-way lexical order.
1 a, b := []int{1, 2}, []int{1, 2}
2 a == b // compile error: slice can only be compared to nil
3 slices.Equal(a, b) // true
4 slices.Equal(nil, []int{}) // true
5 reflect.DeepEqual([]int(nil), []int{}) // falseReal scenario: table-driven tests comparing results; detecting whether a user's role list changed before writing an audit event; cache invalidation when a configuration map changes.
| Compare | Use | nil vs empty |
|---|---|---|
| Arrays | == | — |
| Slices | slices.Equal, bytes.Equal | Equal |
| Maps | maps.Equal | Equal |
| Anything nested | reflect.DeepEqual or go-cmp | Different |
Fix / how to use it: slices.Equal/maps.Equal in code and tests; avoid reflect.DeepEqual for API results that may be nil or empty.
Performance: preallocation, value vs pointer elements Important
In plain words: most slice cost is in allocations and copies during growth. If you know (or can bound) the final size, allocate once. Store small structs by value; pointers cost one allocation each and make the GC scan more.
Common misunderstanding: "[]*T is faster because copying pointers is cheaper." Building []*T means one heap allocation per element and pointer-chasing on every read; []T with values is one contiguous block. Another: "preallocate everything." Over-allocating for rare large cases wastes memory on every common small case.
Definition: preallocation: make([]T, 0, n) or slices.Grow(s, n); for maps make(map[K]V, n). Measured on this machine (Apple M4 Pro, Go 1.27.4, 10 000 64-byte structs, go test -bench): growing from nil 175 µs, 2.65 MB, 19 allocs/op; preallocated 55 µs, 0.65 MB, 1 alloc/op; pointer elements 129 µs, 10 001 allocs/op.
1 var out []Order // 19 allocations for 10 000 appends
2 out := make([]Order, 0, len(rows)) // 1 allocation
3 out := make([]*Order, 0, len(rows)) // 1 + 10 000 allocations
4 counts := make(map[string]int, len(words)) // avoids rehash steps while fillingReal scenario: converting pgx rows to structs (make([]T, 0, expected)); building a response slice in a handler that runs 10 000 times per second; a cache storing map[string]*BigStruct because entries are shared across goroutines.
| Element | Allocation per element | GC scan | Mutation through slice |
|---|---|---|---|
[]T small struct | None | Only if T has pointers | s[i].f = v works |
[]T huge struct (KBs) | None | Same | Copy on range value variable |
[]*T | One each | Every element | Shared identity |
Fix / how to use it: preallocate with known sizes; use values for small structs and index (for i := range s { s[i].f = … }) instead of the range value copy; measure with testing.AllocsPerRun and benchmarks (Testing & Benchmarking). Code: prealloc.
Mechanics
Runtime representation Good to know
| Value | What the variable holds (64-bit) | unsafe.Sizeof | Where the elements live |
|---|---|---|---|
[4]int64 | The 4 elements themselves | 32 | Inline (stack, struct field, or inside another array) |
[]int64 | {array *T, len int, cap int} | 24 | Separate backing array (heap, or stack if it does not escape) |
string | {ptr *byte, len int} | 16 | Read-only bytes (static data or heap) |
map[K]V | Pointer to a runtime Map | 8 | Directory, tables, groups (heap) |
[]T inside a struct | The 24-byte header | 24 | Shared with any copy of the struct |
Escape analysis decides heap vs stack: go build -gcflags=-m prints make([]Order, 0, n) escapes to heap for a returned slice. Since Go 1.25 the compiler can also give a local slice that never escapes a small stack buffer for its first appends (that is the cap 0 → 4 jump for []int64 and 0 → 32 for []byte in the lab), and Go 1.26 extended this; the release notes describe the bisect flag -compile=variablemake and the switch -gcflags=all=-d=variablemakehash=n to find or disable these stack allocations.
Every error, verbatim Must-know
All of these were produced on Go 1.27.4 by the lab or by a scratch file (compile errors).
| Message | Kind | Cause | Fix |
|---|---|---|---|
panic: runtime error: index out of range [3] with length 3 | Panic (recoverable) | s[i] with i >= len(s) | Check len, or range |
panic: runtime error: slice bounds out of range [:5] with capacity 4 | Panic | s[:j] with j > cap(s) | Clamp j |
panic: runtime error: slice bounds out of range [3:2] | Panic | low > high | Validate offsets |
panic: runtime error: makeslice: len out of range | Panic | Negative or huge make length | Validate sizes from input |
panic: runtime error: cannot convert slice with length 2 to array or pointer to array with length 3 | Panic | [3]int(s) with short s | Check len(s) first |
panic: assignment to entry in nil map | Panic | Write to var m map[K]V | make the map |
panic: runtime error: hash of unhashable type []int | Panic | Slice as dynamic key in map[any]V | Use a comparable key |
fatal error: concurrent map writes | Fatal, NOT recoverable | Two goroutines writing | Mutex / sync.Map |
fatal error: concurrent map read and map write | Fatal | Reader and writer | Mutex (RWMutex) |
fatal error: concurrent map iteration and map write | Fatal | range while another goroutine writes | Lock, or iterate a snapshot |
WARNING: DATA RACE | Race detector report | Unsynchronised access seen by -race | Same as above; run go test -race in CI |
invalid operation: a == b (slice can only be compared to nil) | Compile | == on slices | slices.Equal |
invalid map key type []int | Compile | Slice/map/func key | Array or struct key |
cannot assign to struct field m["a"].X in map | Compile | Map elements are not addressable | Read-modify-write, or map[K]*T |
invalid operation: cannot take address of m["a"] (map index expression of struct type P) | Compile | &m[k] | Same |
Read passes lock by value: ….Counter contains sync.Mutex | go vet (copylocks) | Struct with mutex passed by value | Pass *Counter |
Growth arithmetic and size classes Important
growslice works in two steps. First nextslicecap picks an element count: the needed length if it is more than double, double below 256, otherwise repeatedly newcap += (newcap + 768) / 4. Then roundupsize rounds the byte size up to the allocator's size class, and the capacity becomes rounded bytes / element size. That is why the lab shows 512 → 848 for []int64 (832 × 8 = 6656 B → class 6784 B → 848 elements) and 512 → 896 for []byte (832 B → class 896 B). Appending many elements at once (append(s, big...)) jumps straight to the needed length when it is more than double, then rounds up.
1 oldCap=1024, need 1025: 1024 + (1024+768)/4 = 1472 factor 1.44
2 oldCap=4096, need 4097: 4096 + (4096+768)/4 = 5312 factor 1.30
3 oldCap=1e6, need 1e6+1: 1e6 + (1e6+768)/4 = 1250192 factor 1.25
4 append(make([]int, 0, 2), 10 elements...) -> newLen 10 > 2*2, cap 10 (then size-class rounding)The tools Must-know
| Tool | What it shows here | Command |
|---|---|---|
| Race detector | Unsynchronised map/slice access with both stacks | go test -race ./... |
go vet | copylocks (mutex in a copied struct), loopclosure on old code | go vet ./... |
| Escape analysis | Which make/append go to the heap | go build -gcflags=-m ./pkg |
| Allocation counting | Allocations per call in a test | testing.AllocsPerRun(n, f) |
| Benchmarks | ns/op, B/op, allocs/op | go test -bench . -benchmem |
| Heap profile | Who retains big arrays (sub-slice leaks) | go tool pprof -sample_index=inuse_space heap.out |
GOEXPERIMENT=noswissmap | Old map implementation (Go 1.24 only; removed later) | GOEXPERIMENT=noswissmap go test ./... |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Caller's data overwritten by append | Full slice expression | s[a:b:b], slices.Clip | No copy | Still shares for writes |
| Caller keeps or mutates the result | Clone | slices.Clone, bytes.Clone | Fully independent | One allocation + copy |
| Many reallocations | Preallocate | make([]T, 0, n), slices.Grow | One allocation | Need a size estimate |
| Big array retained | Copy out | bytes.Clone, strings.Clone | GC frees the big buffer | Copy cost |
| Filter without allocating | In place | s[:0] + append, slices.DeleteFunc | Zero allocations | Destroys input |
null in JSON | Normalise | []T{}, map[K]V{} at the boundary | Stable contract | One small allocation |
| Missing vs zero | Comma-ok | v, ok := m[k] | Explicit | None |
| Struct in map not updatable | Write back or pointers | a := m[k]; …; m[k] = a | Keeps values compact | Two copies |
| Shared map across goroutines | Lock or sync.Map | RWMutex + map | Correct, typed | Contention |
| Non-deterministic output | Sort keys | slices.Sorted(maps.Keys(m)) | Deterministic | O(n log n) |
| Equal priorities reorder | Stable sort or tie-breaker | SortStableFunc, cmp.Or | Predictable | Stable is a bit slower |
| Map memory stays high | Rebuild | maps.Clone or new map + copy | Frees old tables | Copy cost, brief double memory |
Arrays as values and keys
// Package arrays shows that Go arrays are values: fixed size, copied on
// assignment and on function calls, comparable with ==, usable as map keys.
package arrays
// RGB is a fixed-size value. Its length (3) is part of its type.
type RGB [3]uint8
// Brighten receives a COPY of c; the caller's array is unchanged.
func Brighten(c RGB) RGB {
for i := range c {
if c[i] <= 245 {
c[i] += 10
}
}
return c
}
// BrightenInPlace takes a pointer to the array, so it mutates the caller's value.
func BrightenInPlace(c *RGB) {
for i := range c { // ranging over *array works and indexes the pointee
if c[i] <= 245 {
c[i] += 10
}
}
}
// Point is a comparable array type, so it can be a map key.
type Point [2]int
// Visited counts how often each grid point was seen.
func Visited(path []Point) map[Point]int {
seen := make(map[Point]int, len(path))
for _, p := range path {
seen[p]++
}
return seen
}
// Digest is the shape of crypto hashes such as sha256.Sum256: a [32]byte value.
type Digest [32]byte
// Equal compares two digests with == (element-wise, no loop needed).
func Equal(a, b Digest) bool { return a == b }
// FromSlice converts a slice to an array (Go 1.20+). It copies the elements;
// it panics if len(s) < 4.
func FromSlice(s []byte) [4]byte { return [4]byte(s) }Reproducing the growth formula
The test asserts the real capacities never fall below the formula and that the factor approaches 1.25; it does not pin exact numbers, which change with size classes and compiler versions.
// Package growth records how append grows a slice's capacity.
package growth
// Trace appends n int64 values one by one and returns every capacity the
// slice passed through, starting from the nil slice's 0.
func Trace(n int) []int {
var s []int64
caps := []int{cap(s)}
for i := 0; i < n; i++ {
s = append(s, int64(i))
if c := cap(s); c != caps[len(caps)-1] {
caps = append(caps, c)
}
}
return caps
}
// NextCap reproduces the formula in runtime.nextslicecap (Go 1.20+) for a
// single growth step, BEFORE the runtime rounds the byte size up to a
// malloc size class. Real capacities are therefore equal or larger.
func NextCap(newLen, oldCap int) int {
newcap := oldCap
doublecap := newcap + newcap
if newLen > doublecap {
return newLen
}
const threshold = 256
if oldCap < threshold {
return doublecap
}
for {
// From 2x for small slices towards 1.25x for large ones.
newcap += (newcap + 3*threshold) >> 2
if uint(newcap) >= uint(newLen) {
break
}
}
if newcap <= 0 {
return newLen
}
return newcap
}Aliasing, in-place filtering and buffer reuse
// Package aliasing collects the shared-backing-array patterns: in-place
// filtering with s[:0], buffer reuse, copy semantics and the append
// "sometimes shares" trap.
package aliasing
// KeepPositive filters in place: the result reuses s's array. The caller
// must stop using the old s. Elements past the new length are zeroed so that
// pointers in them (if any) do not keep objects alive.
func KeepPositive(s []int) []int {
out := s[:0]
for _, v := range s {
if v > 0 {
out = append(out, v)
}
}
clear(s[len(out):])
return out
}
// Batcher reuses one buffer for every batch: no allocation per batch after
// the first. Flush receives a view that is only valid during the call.
type Batcher struct {
buf []string
size int
Flush func(batch []string)
}
// NewBatcher allocates the buffer once with the batch size as capacity.
func NewBatcher(size int, flush func([]string)) *Batcher {
return &Batcher{buf: make([]string, 0, size), size: size, Flush: flush}
}
// Add appends one item and flushes when the batch is full.
func (b *Batcher) Add(item string) {
b.buf = append(b.buf, item)
if len(b.buf) == b.size {
b.Done()
}
}
// Done flushes what is left and resets the length, keeping the capacity.
func (b *Batcher) Done() {
if len(b.buf) == 0 {
return
}
b.Flush(b.buf)
clear(b.buf) // drop string references before reuse
b.buf = b.buf[:0]
}
// SharesAfterAppend reports whether append(s, v) wrote into s's array. It
// is true exactly when len(s) < cap(s): the classic "it depends" of append.
func SharesAfterAppend(s []int, v int) bool {
t := append(s, v)
return len(s) > 0 && &t[0] == &s[0]
}
// ShiftLeft uses copy with overlapping source and destination, which is
// defined behaviour (copy works like memmove).
func ShiftLeft(s []int, n int) []int {
if n >= len(s) {
return s[:0]
}
copied := copy(s, s[n:])
return s[:copied]
}Releasing big buffers
// Package leak shows how a tiny sub-slice keeps a huge backing array alive,
// and the two fixes: copy the bytes out, or clip and clone.
package leak
import "bytes"
// FirstLineLeaky returns a view into data. While the caller keeps the
// result, the garbage collector cannot free data, even if it is 64 MiB.
func FirstLineLeaky(data []byte) []byte {
if i := bytes.IndexByte(data, '\n'); i >= 0 {
return data[:i]
}
return data
}
// FirstLine copies the line into a right-sized array of its own.
func FirstLine(data []byte) []byte {
return bytes.Clone(FirstLineLeaky(data))
}
// Session holds pointers; shrinking a slice of pointers without zeroing the
// tail keeps the dropped sessions reachable through the backing array.
type Session struct {
ID string
Cache []byte
}
// DropFirst removes the first n sessions and zeroes the vacated slots so
// the GC can reclaim them. (slices.Delete does the same since Go 1.22.)
func DropFirst(s []*Session, n int) []*Session {
if n > len(s) {
n = len(s)
}
m := copy(s, s[n:])
clear(s[m:])
return s[:m]
}nil vs empty at the JSON boundary
// Package nilempty shows the one place where nil and empty slices (and maps)
// differ in practice: encoding/json.
package nilempty
import "encoding/json"
// Response is an API payload. Without care, "no orders" becomes null.
type Response struct {
Orders []string `json:"orders"`
Meta map[string]string `json:"meta"`
}
// Encode marshals r as is.
func Encode(r Response) (string, error) {
b, err := json.Marshal(r)
return string(b), err
}
// EncodeStable normalises nil to empty so clients always get [] and {}.
func EncodeStable(r Response) (string, error) {
if r.Orders == nil {
r.Orders = []string{}
}
if r.Meta == nil {
r.Meta = map[string]string{}
}
return Encode(r)
}The slices package on a real task
// Package slicesdemo is a tour of the generic slices package (Go 1.21+) and
// its iterator functions (Go 1.23+), applied to one realistic task.
package slicesdemo
import (
"cmp"
"maps"
"slices"
"strings"
)
// Product is a catalogue row.
type Product struct {
SKU string
Price int // cents
}
// NormaliseTags lower-cases, sorts and de-duplicates tags. Compact only
// removes ADJACENT duplicates, so it must run after Sort.
func NormaliseTags(tags []string) []string {
out := slices.Clone(tags) // never sort the caller's slice behind their back
for i, t := range out {
out[i] = strings.ToLower(strings.TrimSpace(t))
}
slices.Sort(out)
out = slices.Compact(out)
return slices.Clip(out) // drop spare capacity so callers' appends allocate
}
// HasTag uses BinarySearch, which requires a sorted slice: O(log n).
func HasTag(sorted []string, tag string) bool {
_, found := slices.BinarySearch(sorted, tag)
return found
}
// InsertSorted keeps sorted order without re-sorting.
func InsertSorted(sorted []string, tag string) []string {
i, found := slices.BinarySearch(sorted, tag)
if found {
return sorted
}
return slices.Insert(sorted, i, tag)
}
// RemoveSKU deletes the first product with sku. Since Go 1.22 Delete zeroes
// the vacated tail element, so the old view no longer shows a stale copy.
func RemoveSKU(ps []Product, sku string) []Product {
i := slices.IndexFunc(ps, func(p Product) bool { return p.SKU == sku })
if i < 0 {
return ps
}
return slices.Delete(ps, i, i+1)
}
// ByPrice sorts by price, then SKU, with a three-way comparison function.
func ByPrice(ps []Product) {
slices.SortFunc(ps, func(a, b Product) int {
return cmp.Or(cmp.Compare(a.Price, b.Price), strings.Compare(a.SKU, b.SKU))
})
}
// Merge concatenates catalogues in one allocation (Go 1.22+).
func Merge(parts ...[]Product) []Product {
return slices.Concat(parts...)
}
// SKUs collects keys of a map into a sorted slice with iterators (Go 1.23+).
func SKUs(stock map[string]int) []string {
return slices.Sorted(maps.Keys(stock))
}
// Expensive ranges over slices.All, which yields (index, value) exactly like
// range over the slice; it exists for APIs that accept an iter.Seq2.
func Expensive(ps []Product, min int) []Product {
var out []Product
for _, p := range slices.All(ps) {
if p.Price >= min {
out = append(out, p)
}
}
return out
}
// Prices maps products to prices: Values iterates, Collect materialises.
func Prices(ps []Product) []int {
prices := make([]int, 0, len(ps))
for p := range slices.Values(ps) {
prices = append(prices, p.Price)
}
return slices.Collect(slices.Values(prices))
}
// Newest returns a reversed copy, newest first.
func Newest(ids []int) []int {
out := slices.Clone(ids)
slices.Reverse(out)
return out
}
// Reserve guarantees room for n more items without reallocating later.
func Reserve(ps []Product, n int) []Product {
return slices.Grow(ps, n)
}Stable sorting
// Package sortstable contrasts sort.Slice / slices.SortFunc (not stable,
// pdqsort) with sort.SliceStable / slices.SortStableFunc (stable).
package sortstable
import (
"cmp"
"slices"
"sort"
)
// Ticket arrives in time order; we sort it by priority only.
type Ticket struct {
ID int
Priority int
}
// ByPriorityStable keeps arrival order among equal priorities, which is what
// a support queue needs ("first come, first served within a priority").
func ByPriorityStable(ts []Ticket) {
slices.SortStableFunc(ts, func(a, b Ticket) int { return cmp.Compare(a.Priority, b.Priority) })
}
// ByPriorityLegacy is the pre-1.21 spelling, still stable.
func ByPriorityLegacy(ts []Ticket) {
sort.SliceStable(ts, func(i, j int) bool { return ts[i].Priority < ts[j].Priority })
}
// ByPriorityThenID is deterministic even with an unstable sort, because the
// comparison has a total-order tie-breaker.
func ByPriorityThenID(ts []Ticket) {
slices.SortFunc(ts, func(a, b Ticket) int {
return cmp.Or(cmp.Compare(a.Priority, b.Priority), cmp.Compare(a.ID, b.ID))
})
}Bytes and strings
// Package bytesdemo treats strings as read-only byte slices and shows where
// conversions copy, how append and copy accept strings, and the bytes
// package helpers that mirror strings.
package bytesdemo
import (
"bytes"
"strings"
)
// Upper converts once to []byte (a copy), edits in place, converts back
// (another copy). Strings are immutable, so the original is untouched.
func Upper(s string) string {
b := []byte(s)
for i, c := range b {
if 'a' <= c && c <= 'z' {
b[i] = c - ('a' - 'A')
}
}
return string(b)
}
// AppendLine appends a string to a byte buffer without converting it first:
// append(dst, s...) is a special case the spec allows.
func AppendLine(dst []byte, s string) []byte {
dst = append(dst, s...)
return append(dst, '\n')
}
// CSVRow builds output with bytes.Buffer, which grows its own []byte.
func CSVRow(fields []string) string {
var buf bytes.Buffer
for i, f := range fields {
if i > 0 {
buf.WriteByte(',')
}
buf.WriteString(f)
}
return buf.String()
}
// Join is the strings.Builder version: no final copy in String().
func Join(fields []string) string {
var sb strings.Builder
sb.Grow(len(fields) * 8)
for i, f := range fields {
if i > 0 {
sb.WriteByte(',')
}
sb.WriteString(f)
}
return sb.String()
}
// HeaderValue parses "Key: value" from a raw line using the bytes package,
// which mirrors strings (Cut, TrimSpace, EqualFold, Fields, Split...).
func HeaderValue(line []byte, key string) (string, bool) {
k, v, ok := bytes.Cut(line, []byte(":"))
if !ok || !bytes.EqualFold(bytes.TrimSpace(k), []byte(key)) {
return "", false
}
return string(bytes.TrimSpace(v)), true
}Multi-dimensional layouts
// Package matrix compares the three shapes of multi-dimensional data:
// a fixed array of arrays, a slice of slices, and one flat slice.
package matrix
// Board is a fixed 3x3 array of arrays: one contiguous value, copyable,
// comparable with ==.
type Board [3][3]byte
// Jagged allocates rows independently: rows can have different lengths,
// but each row is a separate allocation (rows+1 allocations).
func Jagged(rows, cols int) [][]float64 {
m := make([][]float64, rows)
for i := range m {
m[i] = make([]float64, cols)
}
return m
}
// Contiguous allocates once and slices rows out of one backing array, the
// layout Effective Go describes. Rows are capped with a full slice
// expression so an append on one row cannot spill into the next.
func Contiguous(rows, cols int) [][]float64 {
cells := make([]float64, rows*cols)
m := make([][]float64, rows)
for i := range m {
m[i] = cells[i*cols : (i+1)*cols : (i+1)*cols]
}
return m
}
// Grid is a flat row-major matrix: the cheapest layout for numeric work.
type Grid struct {
Rows, Cols int
Cells []float64
}
// NewGrid allocates rows*cols cells.
func NewGrid(rows, cols int) Grid {
return Grid{Rows: rows, Cols: cols, Cells: make([]float64, rows*cols)}
}
// At returns the cell at (r, c).
func (g Grid) At(r, c int) float64 { return g.Cells[r*g.Cols+c] }
// Set writes the cell at (r, c).
func (g Grid) Set(r, c int, v float64) { g.Cells[r*g.Cols+c] = v }Maps: comma-ok, sets, structs, NaN
// Package mapsdemo covers the built-in map: zero-value reads, comma-ok,
// sets, maps of structs, delete during range, clear, NaN keys and the maps
// package (Go 1.21+, iterators Go 1.23+).
package mapsdemo
import (
"maps"
"math"
"slices"
"strings"
)
// WordCount relies on the zero value: a missing key reads as 0, so ++ works
// without checking first. The hint avoids rehashing while the map fills.
func WordCount(text string) map[string]int {
words := strings.Fields(text)
counts := make(map[string]int, len(words))
for _, w := range words {
counts[strings.ToLower(w)]++
}
return counts
}
// Price distinguishes "missing" from "present with zero value" (comma-ok).
func Price(prices map[string]int, sku string) (int, bool) {
p, ok := prices[sku]
return p, ok
}
// Set is the idiomatic set: struct{} values take no memory.
type Set[K comparable] map[K]struct{}
// Add inserts k.
func (s Set[K]) Add(k K) { s[k] = struct{}{} }
// Has reports membership.
func (s Set[K]) Has(k K) bool { _, ok := s[k]; return ok }
// Account is stored by value in a map.
type Account struct {
Owner string
Balance int
}
// Deposit cannot write m[id].Balance += n (map elements are not
// addressable); read, modify, write back.
func Deposit(m map[string]Account, id string, n int) {
a := m[id]
a.Balance += n
m[id] = a
}
// DepositPtr stores pointers instead, so the element can be changed in place.
func DepositPtr(m map[string]*Account, id string, n int) {
if a, ok := m[id]; ok {
a.Balance += n
}
}
// PurgeEmpty deletes during range, which the spec allows: deleted entries
// not yet reached are not produced.
func PurgeEmpty(m map[string]Account) {
for id, a := range m {
if a.Balance == 0 {
delete(m, id)
}
}
}
// SortedKeys gives deterministic output; map iteration order is unspecified.
func SortedKeys[V any](m map[string]V) []string {
return slices.Sorted(maps.Keys(m))
}
// Snapshot returns a shallow copy (maps.Clone); pointer values stay shared.
func Snapshot[K comparable, V any](m map[K]V) map[K]V { return maps.Clone(m) }
// Invert builds value->key with maps.All and maps.Collect style iteration.
func Invert(m map[string]int) map[int]string {
out := make(map[int]string, len(m))
for k, v := range maps.All(m) {
out[v] = k
}
return out
}
// NaNKeys shows why NaN keys are a trap: NaN != NaN, so every insert adds a
// new entry that no lookup or delete can ever find. Only clear (Go 1.21+)
// removes them.
func NaNKeys() (lenAfterInserts int, found bool, lenAfterClear int) {
m := map[float64]string{}
m[math.NaN()] = "a"
m[math.NaN()] = "b"
_, found = m[math.NaN()]
lenAfterInserts = len(m)
clear(m)
return lenAfterInserts, found, len(m)
}A map shared between goroutines
The test runs eight goroutines incrementing one key and sixteen racing to fill a sync.Map; it passes under go test -race.
// Package safemap shows the two standard ways to share a map between
// goroutines: a mutex next to a plain map, or sync.Map for its two
// documented use cases.
package safemap
import "sync"
// Counter guards a plain map with a RWMutex. Pass *Counter, never Counter:
// copying a struct that contains a mutex copies the lock (go vet: copylocks).
type Counter struct {
mu sync.RWMutex
m map[string]int
}
// NewCounter allocates the map; the zero Counter would panic on first Inc.
func NewCounter() *Counter { return &Counter{m: make(map[string]int)} }
// Inc adds one under the write lock.
func (c *Counter) Inc(key string) {
c.mu.Lock()
c.m[key]++
c.mu.Unlock()
}
// Get reads under the read lock; many readers can hold it at once.
func (c *Counter) Get(key string) int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.m[key]
}
// Snapshot copies the map while holding the lock, so callers can range over
// the result without racing with writers.
func (c *Counter) Snapshot() map[string]int {
c.mu.RLock()
defer c.mu.RUnlock()
out := make(map[string]int, len(c.m))
for k, v := range c.m {
out[k] = v
}
return out
}
// Registry is a write-once, read-many cache: sync.Map's first use case.
type Registry struct{ m sync.Map }
// LoadOrCreate returns the existing value or stores the new one atomically.
// build may run more than once under contention; only one result is kept.
func (r *Registry) LoadOrCreate(key string, build func() any) any {
if v, ok := r.m.Load(key); ok {
return v
}
v, _ := r.m.LoadOrStore(key, build())
return v
}Preallocation and pointer elements
TestAllocationCounts asserts exactly 1 allocation for the preallocated version and at least 10 000 for pointer elements.
// Package prealloc compares growing a slice from nil with preallocating the
// known final size, and value vs pointer elements.
package prealloc
// Order is a 64-byte value.
type Order struct {
ID int64
Customer int64
Cents int64
Status [5]int64
}
// Grow appends to a nil slice: several reallocations and copies.
func Grow(n int) []Order {
var out []Order
for i := 0; i < n; i++ {
out = append(out, Order{ID: int64(i)})
}
return out
}
// Prealloc uses make with length 0 and capacity n: exactly one allocation.
func Prealloc(n int) []Order {
out := make([]Order, 0, n)
for i := 0; i < n; i++ {
out = append(out, Order{ID: int64(i)})
}
return out
}
// Pointers stores *Order: one allocation per element plus the slice, and
// the GC must scan every pointer. Use it only when elements must be shared
// or mutated through several references.
func Pointers(n int) []*Order {
out := make([]*Order, 0, n)
for i := 0; i < n; i++ {
out = append(out, &Order{ID: int64(i)})
}
return out
}Go
The page's main example: a pagination helper for an audit log. Both versions compile and pass a simple test; only one survives a caller that appends.
Before
Page returns events[from:to], whose capacity reaches the rest of the log. WithMarker appends a synthetic event, which lands in events[to]: the next page loses a real event. The test in before/window_test.go asserts that this overwrite happens.
// Package before returns sub-slices that share the caller's backing array.
// It compiles and passes simple tests, but every caller that appends to the
// result can silently overwrite the caller's data.
package before
// Event is one row of an audit log.
type Event struct {
ID int
Action string
}
// Page returns events[from:to]. The result has spare capacity that reaches
// into events[to:], so append writes over the next page.
func Page(events []Event, from, to int) []Event {
return events[from:to]
}
// WithMarker adds a synthetic "page-end" event to a page before rendering.
func WithMarker(page []Event) []Event {
return append(page, Event{ID: -1, Action: "page-end"})
}After
Page uses events[from:to:to], so the first append must reallocate; PageCopy clones when the page outlives the request or the source is a big buffer.
// Package after returns pages that cannot write into the caller's array.
package after
import "slices"
// Event is one row of an audit log.
type Event struct {
ID int
Action string
}
// Page uses a full slice expression: cap(result) == len(result), so the
// first append must allocate a new array and the caller's data is safe.
// The page still shares memory for reads (no copy).
func Page(events []Event, from, to int) []Event {
return events[from:to:to]
}
// PageCopy returns an independent copy. Use it when the page outlives the
// request or the source is a large buffer you want the GC to free.
func PageCopy(events []Event, from, to int) []Event {
return slices.Clone(events[from:to])
}
// WithMarker adds a synthetic "page-end" event to a page before rendering.
func WithMarker(page []Event) []Event {
return append(page, Event{ID: -1, Action: "page-end"})
}The Go angle
- The standard library follows the same rules.
bufio.Reader.ReadSliceandbytes.Fieldsreturn views into existing memory;bytes.Clone,strings.Cloneandslices.Cloneexist precisely to break that sharing.io.ReadAllreturns a fresh slice (Go 1.26 made it "a minimally sized final slice"). database/sqlandpgxreuse buffers.sql.RawBytes"holds a reference to memory owned by the database itself" and is only valid until the nextNext/Scan; scan into[]byte(copied) if you keep it. Details in database/sql & pgx.encoding/jsonreuses what you decode into. Go 1.27'sUnmarshaldocs: it decodes array elements into the existing slice, "reusing existing slice elements in-place", and for maps it "reuses the existing map, keeping existing entries"; decoding into a reused struct can therefore leave stale map entries. See JSON, XML, Struct Tags.- Generics made the helpers possible.
slices.Sort[S ~[]E, E cmp.Ordered]works on named slice types too; writing your own is covered in Generics. - The
rangestatement copies each element into the loop variable; for large structs iterate by index. Per-iteration variables since Go 1.22 removed the old "all closures see the last element" bug (Control Flow).
For PHP/Laravel developers
A PHP array is one structure that is simultaneously a list, a hash map and an ordered dictionary. The PHP manual: "An array in PHP is actually an ordered map. A map is a type that associates values to keys." Go splits that into three types with different costs, and none of them is ordered by key insertion.
<?php
// PHP: one type, value semantics with copy-on-write, insertion order preserved.
$a = ['b' => 2, 'a' => 1];
$b = $a; // logically a copy (copied lazily on first write)
$b['c'] = 3; // $a unchanged
foreach ($a as $k => $v) { echo $k; } // always "b", then "a": insertion order
$list = [1, 2, 3];
$list[] = 4; // append; no capacity concept visible
unset($list[1]); // leaves a hole: keys 0, 2, 3 (array_values() to reindex)| PHP | Go | Difference that bites |
|---|---|---|
$list = [1, 2, 3] | s := []int{1, 2, 3} | Go slice assignment shares elements; PHP copies on write |
$list[] = 4 | s = append(s, 4) | Must assign the result; may reallocate |
['k' => 'v'] | map[string]string{"k": "v"} | Go map order is random; PHP keeps insertion order |
isset($m['k']) / array_key_exists | _, ok := m["k"] | isset is false for null values; comma-ok is exact |
count($a) | len(s), len(m) | Same idea |
array_slice($a, 1, 2) | s[1:3] | Go returns a view, PHP a copy |
sort($a) / usort | slices.Sort / slices.SortFunc | PHP 8's sort is stable; Go's SortFunc is not |
array_unique($a) | slices.Sort + slices.Compact | Compact needs sorted input |
in_array($x, $a, true) | slices.Contains(s, x) | Same O(n) |
array_merge($a, $b) | slices.Concat(a, b) | |
Laravel collect($a)->filter()->values() | slices.DeleteFunc or a loop | No lazy collection object; iterators (1.23) are the closest |
json_encode([]) → [] | nil slice → null | Normalise nil to empty at the API edge |
| PHP-FPM: one request per process, no shared arrays | Goroutines share memory | A package-level Go map is shared by every request: lock it |
The last row is the important one for a Laravel developer: in PHP-FPM each request has its own memory, so a static array can never be written by two requests at once. In Go, a package-level map is visible to every goroutine serving every request, and the first concurrent write kills the process. Laravel Octane (Swoole/RoadRunner/FrankenPHP) introduces the same class of problem with state that survives between requests.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| Fixed-size identity (hash, IP, coordinate) | Array [N]T | Use as map key | Comparable, no allocation |
| Rows from a query, known count | make([]T, 0, n) | Value elements | One allocation |
| Unknown count, small | var s []T + append | — | Growth is cheap at small sizes |
| Returning part of an internal slice | s[a:b:b] | Document "view" | No copy, safe appends |
| Storing part of a big buffer | bytes.Clone / slices.Clone | — | Avoid retaining the buffer |
| Filter a slice you own | slices.DeleteFunc | — | Zero allocations, tail zeroed |
| Unique sorted values | slices.Sort + slices.Compact | slices.Clip | Linear after sort |
| Membership in a big, static list | Sorted slice + BinarySearch, or map[K]struct{} | — | O(log n) and compact vs O(1) and larger |
| Lookup by ID | map[K]V with make(…, n) | Comma-ok | O(1) average |
| Deterministic output | slices.Sorted(maps.Keys(m)) | — | Map order is random |
| Shared map, mixed reads/writes | Struct with sync.RWMutex + map | Snapshot for iteration | Typed, simple |
| Write-once cache / disjoint keys per goroutine | sync.Map | LoadOrStore | Fewer lock contentions |
| JSON array field | Never nil at the boundary | []T{} | [] instead of null |
| Sort with meaningful ties | slices.SortStableFunc | or cmp.Or tie-breaker | Predictable order |
| Matrix / image | Flat []T with stride | Or rows over one buffer | One allocation, cache-friendly |
In architecture: from a single process to a distributed system
Slices and maps are in-process structures, but the decisions you make with them leak into API contracts, database queries and memory budgets as a system grows.
Monolith: one process, one database
The simplest correct use: build result slices with preallocated capacity from rows, keep request-scoped maps local to the handler, and never store request data in package-level maps. A typical case is loading items for a list of IDs: pass the slice as one array parameter instead of building an IN (...) string, and chunk very large lists so one query does not carry 100 000 parameters.
-- pgx sends a Go []int64 as a PostgreSQL bigint[]; one round trip, one plan
SELECT id, sku, price_cents
FROM products
WHERE id = ANY($1::bigint[]);1 handler gets ids []int64 (10 000)
2 for chunk := range slices.Chunk(ids, 1000) -> 10 queries, each WHERE id = ANY($1)
3 rows -> out := make([]Product, 0, len(ids))
4 byID := make(map[int64]Product, len(out)) -> re-order to the request's orderModular monolith and multiple databases
Module boundaries are where aliasing bugs cross teams: module A returns a slice of its cached data, module B appends to it or sorts it. The rule at a module boundary is "return copies or clipped views, accept slices read-only". A module that caches lookups (country codes, feature flags) in a map owns that map behind a type with a mutex; other modules see only methods. When each module has its own database, joining data in Go means building map[ID]T indexes from one result set and looking up while ranging over another; size the map with make(…, len(rows)).
Microservices
At a service boundary, nothing survives except bytes. Three properties matter. First, JSON: a nil slice becomes null, and a consumer written in TypeScript or PHP may crash on it; normalise to [] in the response DTO (nilempty). Second, order: a map serialised by encoding/json has sorted keys, but anything you range over yourself (signatures, CSV columns, event payload fields) is random unless you sort. Third, size: a request carrying a list must have a maximum length validated before make, or one call can allocate gigabytes.
order-service catalog-service
1 POST /prices {"skus": [...500]} -> validate len(skus) <= 1000
2 make(map[string]int, len(skus))
3 SELECT ... WHERE sku = ANY($1)
4 <- {"prices": {...}, "missing": []} (never null)
5 comma-ok per SKU: missing vs price 0 (free sample)Distributed data: replicas, caches, sharding
In-process maps used as caches are the "L1" in front of Redis or a replica. They inherit three problems: they never shrink after deletes (rebuild them periodically), they are per-instance (ten pods hold ten different versions, so invalidation needs a broadcast or a short TTL), and they must be locked. Consistent hashing for sharding uses a sorted slice of ring positions and slices.BinarySearch to find the owner of a key; see Consistent Hashing. A replica-lag or cache-staleness bug is not fixed by any slice trick: that is covered in Caching.
Scaling path: 1×, 10×, 100×
| Load | What changes for slices and maps |
|---|---|
| 1× | Plain slices and maps; correctness rules only (aliasing, nil vs empty, locks) |
| 10× | Preallocate in hot handlers; reuse buffers with sync.Pool or s[:0]; RWMutex around read-heavy maps; profile allocations |
| 100× | Shard hot maps (N mutex+map pairs by key hash) or sync.Map for write-once caches; bound cache sizes (LRU) because maps never shrink; flat slices of values instead of []*T to cut GC work; move large shared caches out of process (Redis) |
Lab
Everything here runs on the host with no containers. The outputs below are real, captured on Go 1.27.4 darwin/arm64 (Apple M4 Pro); file paths in the race report are shortened. Capacities and timings will differ on other versions and machines; the shapes will not.
cd docs/snippets/go/arrays-slices-maps/go
go vet ./... && go test -race ./...1. Watch append grow.
$ go run ./cmd/lab growth
[]int64 caps: [0 4 8 16 32 64 128 256 512 848 1280 1792 2560]
[]byte caps: [0 32 64 128 256 512 896 1408 2048]2. Two appends to one base.
$ go run ./cmd/lab alias
a: [0 0 0 2] b: [0 0 0 2] same array: true
a: [0 0 0 2] c: [100 0 0 2 3]3. Map iteration order. Run it twice; the lines differ between runs too.
$ go run ./cmd/lab order
d e a b c
a b c d e
d e a b c4. nil vs empty in JSON.
$ go run ./cmd/lab json
{"empty":[],"nil":null}5. The panics and the fatal error. Note that writes ends with fatal error, not panic: no recover can stop it.
$ go run ./cmd/lab index
panic: runtime error: index out of range [3] with length 3
$ go run ./cmd/lab nilmap
read from nil map: 0
panic: assignment to entry in nil map
$ go run ./cmd/lab writes
fatal error: concurrent map writes6. The race detector on a map (a two-goroutine test written for this lab, not part of the module):
$ go test -race ./rc
==================
WARNING: DATA RACE
Write at 0x00c00010aab0 by goroutine 7:
runtime.mapaccess2_fast64()
.../src/internal/runtime/maps/runtime_fast64.go:22 +0x2ac
Previous write at 0x00c00010aab0 by goroutine 8:
runtime.mapaccess2_fast64()7. Preallocation and layout, measured.
$ go test -run '^$' -bench . -benchmem -benchtime=200x ./prealloc ./matrix
BenchmarkGrow-12 200 175509 ns/op 2654247 B/op 19 allocs/op
BenchmarkPrealloc-12 200 55443 ns/op 647179 B/op 1 allocs/op
BenchmarkPointers-12 200 129299 ns/op 721921 B/op 10001 allocs/op
BenchmarkJagged-12 200 12026 ns/op 89601 B/op 100 allocs/op
BenchmarkContiguous-12 200 4611 ns/op 81920 B/op 1 allocs/op8. Escape analysis.
$ go build -gcflags=-m ./prealloc
prealloc/prealloc.go:17:15: append escapes to heap
prealloc/prealloc.go:24:13: make([]Order, 0, n) escapes to heap
prealloc/prealloc.go:37:21: &Order{...} escapes to heapCommon misconceptions
| Belief | Reality |
|---|---|
| Slices are passed by reference | The header is passed by value; elements are shared, length and capacity are not |
append always copies | Only when len+n > cap; otherwise it writes into the shared array |
| Capacity doubles forever | 2x below 256 elements, then about 1.25x, plus size-class rounding |
make([]T, n) reserves room | It creates n zero elements; use make([]T, 0, n) to reserve |
s[a:b:b] copies | It only caps capacity; writes are still shared |
| A small sub-slice is small in memory | It keeps the whole backing array alive |
| nil slices are dangerous | len, range, append work; only JSON and == nil differ |
| Maps iterate in insertion order | Order is unspecified and randomised |
fmt.Println(m) proves the order is stable | fmt sorts keys for printing since Go 1.12 |
| A concurrent map write is a harmless race | It is fatal error: concurrent map writes; the process dies |
sync.Map is the default concurrent map | It is for write-once or disjoint-key workloads; a mutex is the default |
delete frees map memory | Maps never shrink; rebuild to reclaim |
maps.Clone is a deep copy | It is shallow |
slices.Compact removes all duplicates | Only adjacent ones; sort first |
slices.SortFunc keeps ties in order | It is not stable; use SortStableFunc |
Cheat sheet
| Topic | What to remember |
|---|---|
| Array | Value; [N]T; copied on assign; == and map key OK |
| Slice header | ptr, len, cap; 24 bytes; copying it shares elements |
make | make([]T, len, cap); make(map[K]V, hint); maps must be made before writing |
append | Always s = append(s, …); shares if it fits, reallocates if not |
| Growth | 2x under 256, then += (cap+768)/4, then size class |
| Sub-slice | s[a:b] cap = cap(s)-a; use s[a:b:b] to stop spills |
copy | Copies min(len); never grows dst; overlap OK |
| Reuse | s[:0] keeps capacity; clear the tail if it holds pointers |
| Leaks | Clone pieces of big buffers you keep |
| nil vs empty | Same behaviour except == nil, reflect, JSON (null vs []) |
slices | Sort, BinarySearch, Compact (sorted), Delete (zeroes tail 1.22), Insert, Concat, Clone, Grow, Clip |
| Iterators | slices.Sorted(maps.Keys(m)), Collect, Values, All, Chunk (views) |
| Map read | Missing key = zero value; v, ok := m[k] to tell apart |
| Map order | Random; sort keys for output |
| Map mutation | delete in range OK; clear(m); struct elements not addressable |
| Map internals | Go 1.24 Swiss tables: groups of 8, 7/8 load, tables ≤ 1024, split; never shrinks |
| Concurrency | Readers only: OK. Any writer: mutex, or sync.Map for its two cases |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — s := make([]int, 3, 10); t := append(s, 1); u := append(s, 2). What is t[3]? Must-know
Answer
Answer: 2. Both appends fit in capacity 10, so both write into index 3 of the same backing array; the second write wins and t sees it. See Aliasing.
2 — A function receives s []int and does s = append(s, 99). When does the caller see 99? Must-know
Answer
Answer: Never through its own slice's length: the caller's header still has the old len. If the append fitted in capacity, 99 is in the shared array beyond the caller's length (visible only if the caller re-slices up to cap). Return the slice to make the change visible.
3 — What capacity does nextslicecap choose when a slice of capacity 1024 needs one more element, and why might cap() show something larger? Good to know
Answer
Answer: 1024 + (1024 + 768) / 4 = 1472. growslice then rounds the byte size up to a malloc size class, so the real capacity can be larger. See Growth arithmetic.
4 — Why does s[2:4:4] protect the caller but s[2:4] does not? Important
Answer
Answer: s[2:4:4] has capacity 2, so any append must allocate a new array. s[2:4] has capacity cap(s)-2, so an append writes into s[4], which belongs to the caller.
5 — A cache stores line := data[:80] from a 64 MiB file read. What happens to memory and how do you fix it? Important
Answer
Answer: Each cached line keeps its whole 64 MiB array alive. Store bytes.Clone(line) (or string(line)) instead. See Memory leaks.
6 — Your API returns {"items": null} for an empty result. Why, and where do you fix it? Must-know
Answer
Answer: The field is a nil slice, which encoding/json encodes as null. Initialise it to []T{} in the response DTO at the API boundary; keep nil internally.
7 — Why is slices.Compact([]string{"b", "a", "b"}) still three elements? Important
Answer
Answer: Compact removes only consecutive duplicates. Sort first: slices.Sort then slices.Compact gives [a b].
8 — Why does m["acc"].Balance += 5 not compile for map[string]Account, and what are the two fixes? Important
Answer
Answer: Map elements are not addressable (the runtime may move them during growth). Read, modify and write back (a := m[k]; a.Balance += 5; m[k] = a), or store *Account.
9 — Two handlers increment a package-level map[string]int. What is the failure mode and the fix? Must-know
Answer
Answer: The runtime can detect it and abort with fatal error: concurrent map writes, which cannot be recovered, killing all requests. Guard the map with a mutex inside a struct passed by pointer, or use a sharded map; sync.Map only for write-once or disjoint-key patterns.
10 — A map grew to 5 million entries during a backfill and then all but 1 000 were deleted. Does the memory come back? Important
Answer
Answer: No. Go maps do not shrink (issue #20135 is open). Copy the survivors into a new map (maps.Clone allocates for the current size) and drop the old one.
11 — Why is m[math.NaN()] = 1 executed twice a problem? Good to know
Answer
Answer: NaN never equals itself, so each insert creates a new entry, and no lookup or delete can find them. Only clear(m) removes them. Validate float keys.
12 — You sort tickets by priority with slices.SortFunc and support complains that equal-priority tickets jump around. Two fixes? Important
Answer
Answer: slices.SortFunc is not stable. Use slices.SortStableFunc, or add a tie-breaker (cmp.Or(cmp.Compare(a.Priority, b.Priority), cmp.Compare(a.ID, b.ID))).
Glossary
| Term | Meaning |
|---|---|
| Array | Fixed-length sequence [N]T; a value, copied on assignment |
| Slice | Descriptor (ptr, len, cap) of a contiguous segment of an array |
| Slice header | The runtime struct behind a slice: pointer, length, capacity (24 bytes on 64-bit) |
| Length | Number of elements a slice exposes; len(s) |
| Capacity | Elements from the slice's start to the end of the backing array; cap(s) |
| Backing array (underlying array) | The array a slice points into |
| Sub-slice | A slice made by a slice expression from another slice; shares the backing array |
| Aliasing | Two slices referring to overlapping elements of one array |
make | Built-in that creates slices, maps and channels |
append | Built-in that adds elements, reallocating when capacity is exceeded |
growslice | Runtime function that allocates the bigger array for append |
| Growth factor | Ratio new cap / old cap: 2 below 256 elements, tending to 1.25 |
| Size class | Allocator bucket size; capacities are rounded up to fill it |
copy | Built-in copying min(len(dst), len(src)) elements, overlap-safe |
| Three-index slice / full slice expression | s[low:high:max], capacity max-low (Go 1.2) |
clear | Built-in (Go 1.21): zeroes slice elements or deletes all map entries |
| nil slice | Zero-value slice; len 0, encodes as JSON null |
| Empty slice | Non-nil slice with len 0; encodes as JSON [] |
| JSON null | What encoding/json emits for nil slices and maps |
| Memory leak (sub-slice) | A small slice keeping a large backing array reachable |
| Preallocation | Creating a slice/map with its final capacity to avoid regrowth |
slices package | Generic slice helpers (Go 1.21): Sort, BinarySearch, Compact, Clone, Delete, Insert, Concat… |
slices.Sort | In-place pdqsort for ordered types; not stable |
slices.BinarySearch | O(log n) search in a sorted slice; returns index and found |
slices.Compact | Removes consecutive duplicates |
slices.Clone | Shallow copy of a slice |
slices.Delete | Removes s[i:j]; zeroes the vacated tail since Go 1.22 |
slices.Insert | Inserts values at an index, may reallocate |
slices.Concat | Joins slices in one allocation (Go 1.22) |
slices.Collect | Builds a slice from an iterator (Go 1.23) |
slices.Values | Iterator over a slice's elements (Go 1.23) |
slices.Equal | Element-wise equality; nil equals empty |
slices.Grow / slices.Clip | Ensure spare capacity / remove it |
Iterator (iter.Seq) | A function you can range over (Go 1.23) |
| Stable sort | Sort that keeps the input order of equal elements |
| pdqsort | Pattern-defeating quicksort used by slices.Sort |
bytes package | []byte counterparts of strings functions, plus Buffer |
strings.Builder | Efficient string construction without a final copy |
| Multi-dimensional | Arrays of arrays, slices of slices, or flat slices with an index formula |
| Map | Built-in hash map map[K]V; unordered |
| Hash map / hash table | Structure that finds values by hashing keys |
| Bucket | Pre-1.24 map storage unit: 8 key/value pairs plus overflow pointer |
| Swiss table | Open-addressing hash table design used by Go maps since 1.24 |
| Group / control word | 8 slots plus 8 bytes of H2 fingerprints in a Swiss table |
| H1 / H2 | Upper 57 bits (probe position) and lower 7 bits (fingerprint) of the hash |
| Load factor | Used slots / total slots; 7/8 triggers growth in Go 1.24+ maps, 6.5 per bucket before |
| Extendible hashing | Directory of tables selected by hash bits; lets one table split alone |
| Iteration order | Unspecified and randomised for maps |
| Make with hint | make(map[K]V, n): preallocates for about n entries |
delete | Built-in removing one map entry; no-op if missing |
| Comma-ok | v, ok := m[k] form telling missing from zero |
| Zero value | Default value of a type, returned for missing map keys |
| Not addressable | Map elements cannot have their address taken or fields assigned |
| Concurrent map writes | Fatal runtime error when goroutines write a map without synchronisation |
sync.Map | Concurrent map for write-once or disjoint-key workloads |
maps package | Generic map helpers (Go 1.21; iterators 1.23) |
maps.Keys | Iterator over a map's keys (Go 1.23) |
maps.Clone | Shallow copy of a map |
| NaN key | Float key that never equals itself; insertable, never findable |
| Ordered hash map | PHP's array: hash map that remembers insertion order |
| Escape analysis | Compiler pass deciding stack vs heap allocation |
References
Read for this page (Go 1.27 documents unless a version is named); package documentation was read with go doc from Go 1.27.4 because pkg.go.dev returned 403 to the fetcher, so links point to the source files on go.dev.
- Language: The Go Programming Language Specification (array, slice and map types; slice expressions;
append,copy,clear;for range; comparison operators), Effective Go, Go FAQ, The Go Memory Model - Go blog: Go Slices: usage and internals (Gerrand, 2011), Arrays, slices (and strings): The mechanics of 'append' (Pike, 2013), Go maps in action (Gerrand, 2013), Faster Go maps with Swiss Tables (Pratt, 2025), Range Over Function Types, Strings, bytes, runes and characters, Fixing For Loops in Go 1.22
- Release notes: Go 1.2, Go 1.12, Go 1.18, Go 1.20, Go 1.21, Go 1.22, Go 1.23, Go 1.24, Go 1.25, Go 1.26
- Standard library source: slices/slices.go, slices/sort.go, slices/iter.go, maps/maps.go, maps/iter.go, sort/sort.go, bytes/bytes.go, sync/map.go, encoding/json/encode.go, builtin/builtin.go
- Runtime source: runtime/slice.go (
growslice,nextslicecap), internal/runtime/maps/map.go, table.go, group.go, internal/abi/map.go, Go 1.23 runtime/map.go (buckets), Go 1.17 runtime/slice.go (old growth rule) - Go wiki and issues: CodeReviewComments (declaring empty slices), SliceTricks, golang/go#20135 runtime: shrink map as elements are deleted
- PHP: PHP manual: Arrays