Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has three collection types and not oneWhy it exists
Go 1.0 to Go 1.24: who added what, and whenWhere it comes from
[N]T, value semantics, == on arraysArrays are values
Pointer, length, capacityThe slice header
make([]T, len, cap), literals, zero valuesmake, literals and the zero value
How append grows: 2x, then towards 1.25xappend and the growth factor
Two slices, one array, silent overwritesAliasing
s[low:high:max]Full slice expression
copy(dst, src), overlapping copiescopy semantics
s[:0], in-place filters, reused buffersReuse with s[:0]
A 3-byte slice keeping 64 MiB aliveMemory leaks through sub-slices
null vs [] in JSONnil slice vs empty slice
slices.Sort, BinarySearch, Compact, Delete, Insert, Concat…The slices package
slices.All, Values, Collect, SortedIterators
sort.Slice vs slices.Sort, stable sortSorting and stability
[]byte(s), bytes.Buffer, append(b, s...)Strings as byte slices
[][]T, [N][M]T, flat gridsMulti-dimensional data
Zero-value reads, comma-ok, setsMaps
Buckets, load factor, Swiss tables (Go 1.24)Map internals
Why range over a map changes orderIteration order
delete during range, clear, m[k].f = vMutating maps
Which types can be keys, NaNMap key types and NaN
fatal error: concurrent map writes, sync.MapMaps and goroutines
maps.Keys, Values, Clone, Equal, CollectThe maps package
slices.Equal, maps.Equal, reflect.DeepEqualComparing
Preallocation, value vs pointer elementsPerformance
Every panic and compile error verbatimMechanics
Fixes with tested codeSolving the classic problems
Coming from PHP arraysFor PHP/Laravel developers
Monolith to distributed systemIn architecture
Reproduce everything on your laptopLab
Wrong beliefs, cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The three types. Each row is unpacked in the concept catalogue.

TypeIn plain wordsZero valueAssignment / call copiesComparable with ==Usable as map key
Array [N]TN elements in a row; N is part of the typeN zero elements (usable)All N elementsYes, if T isYes, if T is
Slice []TA window (ptr, len, cap) onto an arraynil (len 0, appendable)Only the 24-byte header; elements are sharedOnly with nilNo
Map map[K]VA hash table from keys to valuesnil (readable, NOT writable)Only the pointer; entries are sharedOnly with nilNo
String stringA read-only byte slice (ptr, len)""Only the header; bytes are immutableYesYes

The built-ins and helpers you use daily.

OperationWhat it doesAllocates?Trap
make([]T, n)len n, cap n, all zeroYes (or on stack if it does not escape)append adds AFTER the n zeros
make([]T, 0, n)len 0, cap nYesIndex s[0] panics until you append
append(s, x...)Writes in place if it fits, else growsOnly when len+n > capResult may or may not share s's array
s[a:b]New header, same array, cap = cap(s)-aNoAppends reach into s[b:]
s[a:b:c]Same, but cap = c-aNoc must be ≤ cap(s)
copy(dst, src)Copies min(len(dst), len(src)) elementsNoCopies nothing into a zero-length dst
clear(s) / clear(m)Zeroes elements / deletes all entries (Go 1.21)NoDoes not change len(s)
slices.Clone(s)Independent copy, cap == lenYesShallow: pointers inside are shared
slices.Delete(s, i, j)Removes s[i:j], zeroes the tail (Go 1.22)NoOld views see zeros
make(map[K]V, hint)Preallocates for about hint entriesYesNot a size limit
v, ok := m[k]Comma-ok: tells missing from zeroNom[k] alone returns zero for missing
maps.Keys(m)Iterator over keys (Go 1.23)NoOrder unspecified; wrap in slices.Sorted

The bugs that reach production.

BugSymptomRoot causeFix
Append to a sub-sliceAnother slice's data changesShared backing array, spare capacitys[a:b:b] or slices.Clone
"Sometimes it changes, sometimes not"Flaky testappend shares only when len < capNever rely on either; always use the result
Retained bufferRSS grows; heap profile shows ReadFile6-byte sub-slice keeps 64 MiB arraybytes.Clone, strings.Clone
Write to nil mappanic: assignment to entry in nil mapvar m map[K]V never makedmake in the constructor
Concurrent writesfatal error: concurrent map writes (not recoverable)Map used from two goroutinesMutex, or sync.Map
Ordered output expectedFlaky JSON/golden testsMap order is unspecified and randomisedslices.Sorted(maps.Keys(m))
API returns nullJS client: Cannot read properties of nullnil slice marshals to nullInitialise to []T{}
Loop over index then appendindex out of range [3] with length 3Using make([]T, n) then appendmake([]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 explicitConvenient and implicit
Array: size fixed at compile time, copied on assignmentSlice: size changes, header copied, elements shared
No allocation surprises; can live on the stackappend may allocate and move data behind your back
Comparable, usable as a map keyNot comparable; need slices.Equal
Map with a mutex you ownsync.Map that hides the locking but loses type safety (any)
Sort the keys when you need orderAn 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 ​

  1. "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 append returns a value.
  2. "append always copies" or "append never copies". Both are wrong. It writes into the existing array when len(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.
  3. "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."

VersionChange (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.20Slice → 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.26The 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).

Slice headers (24 bytes each on 64-bit: ptr, len, cap)s := make([]int, 8)ptr=&a[0] len=8 cap=8t := s[2:4]ptr=&a[2] len=2 cap=6u := s[2:4:4]ptr=&a[2] len=2 cap=2Backing array a (one allocation, 8 x int)a[0]a[1]a[2]a[3]a[4]a[5]a[6]a[7]len(t) = len(u) = 2cap(t) = 6: append(t, x) writes into a[4]append(t, 99) fits in cap: it overwrites a[4], which s can see (aliasing).append(u, 99) exceeds cap 2: growslice allocates a new array and copies; a[4] is safe.

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.

text
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 comparison

Real 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.

SituationArray [N]TSlice []T
Size known at compile timeNatural fitWorks, but carries a header
Pass to a functionCopies N elementsCopies 24 bytes
== and map keyAllowed (if T comparable)Compile error
GrowImpossibleappend
Sort with slices.Sortslices.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.

text
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 6

Real 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.

ExpressionlencapShares array with a?
a[i:j]j-icap(a)-iYes
a[i:j:k]j-ik-iYes
a[:0]0cap(a)Yes
a[len(a):]0cap(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.

text
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 map

Real 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.

FormlencapReady for appendReady for s[i] =
var s []T00YesNo
s := []T{}00YesNo
make([]T, n)nnYes (after the zeros)Yes, i < n
make([]T, 0, n)0nYes, no realloc until nNo
make([]T, n, m)nmYesYes, 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):

go
// 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.

s = append(s, x...)len(s)+n ≤ cap(s)?yesWrite in placesame backing array, len growsevery other slice of that arraysees the new elements (aliasing)noruntime.growslice1. nextslicecap: newLen > 2*old → newLen old < 256 → 2*old, else += (old+768)/42. roundupsize to a malloc size class3. mallocgc, memmove old elementsnew header → new array; old array untouchedMeasured on Go 1.27.4, []int64:0 4 8 16 32 64 128 256 512 848 1280 1792 2560factor 2x, then ~1.6x easing to 1.25x; size classes add slack
text
     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 slices

Real 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 capFactor from nextslicecap (before rounding)
< 2562.0
2562.0 (256 + 256 = 512)
5121.625
10241.44
40961.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.

text
     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.

PatternAliases?Safe when
t := s[a:b] then write t[i]YesYou 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])NoAlways (costs a copy)
results = append(results, path) in recursionYesNever: 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)].

text
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 writes

Real 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).

ToolProtects against append spillProtects against writesCopies
s[a:b]NoNoNo
s[a:b:b] / slices.ClipYesNoNo
slices.Clone(s[a:b])YesYesYes

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}.

text
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 left

Real 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).

NeedUse
Independent copy of a sliceslices.Clone(s)
Copy into an existing buffercopy(buf, s) and check the count
String to fresh bytes[]byte(s)
Append one slice to anotherappend(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).

text
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 fill

Real 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.

ApproachAllocationsOld view afterUse when
out := s[:0] + append0Shows filtered prefixYou own s
slices.DeleteFunc(s, f)0Tail zeroedSame, shorter
New slice + append1+Unchangeds is shared
buf = buf[:0] reuse0 per roundOverwritten next roundConsumer 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.

text
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.

LeakDetectFix
Sub-slice of big bufferpprof heap: big allocation sites still livebytes.Clone, slices.Clone
Substring of big stringSamestrings.Clone (Go 1.18)
[]*T shrunk without zeroingObjects survive GCclear(tail), slices.Delete (1.22+)
q = q[1:] queueArray never shrinksRing buffer or periodic slices.Clone
Map that grew then emptiedMemory stays highMake 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.

text
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 nil

Real 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.

Operationnil sliceempty slice
len, cap0, 00, 0
range, appendWorksWorks
s == niltruefalse
json.Marshalnull[]
reflect.DeepEqual(s, []T{})falsetrue
slices.Equal(s, []T{})truetrue

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:

FunctionSinceWhat it doesNote
Sort, SortFunc1.21pdqsort, in place"not guaranteed to be stable"
SortStableFunc1.21Stable sortKeeps order of equal elements
IsSorted, IsSortedFunc1.21Check order
BinarySearch, BinarySearchFunc1.21(index, found) on a sorted sliceO(log n); returns insertion point
Contains, Index, IndexFunc, ContainsFunc1.21Linear searchO(n)
Equal, EqualFunc, Compare1.21Element-wise comparenil equals empty
Compact, CompactFunc1.21Remove consecutive duplicatesZeroes tail since 1.22
Clone1.21Shallow copyPreserves nilness
Grow1.21Ensure room for n more"at least n elements can be appended"
Clip1.21s[:len(s):len(s)]
Delete, DeleteFunc1.21Remove s[i:j] / matching"Delete zeroes the elements s[len(s)-(j-i):len(s)]" (1.22)
Insert1.21Insert values at indexMay reallocate
Replace1.21Replace s[i:j]Zeroes tail since 1.22
Reverse1.21In place
Min, Max, MinFunc, MaxFunc1.21Panics on empty slice
Concat1.22One allocation for all parts
Repeat1.23Repeat a slice n times
text
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".

text
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 ids

Real 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.

WantBefore 1.23Go 1.23+
Sorted map keysloop + append + sort.Stringsslices.Sorted(maps.Keys(m))
Values of a maploop + appendslices.Collect(maps.Values(m))
Batches of nindex arithmeticslices.Chunk(s, n)
Reverse loopfor 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."

text
     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).

APIGenericStableComparison
slices.SortYesNo< on cmp.Ordered
slices.SortFuncYesNofunc(a, b E) int
slices.SortStableFuncYesYesfunc(a, b E) int
sort.SliceNo (any)Noless(i, j int) bool
sort.SliceStableNoYesless(i, j int) bool
sort.Sort / sort.StableNo (interface)No / YesLen, 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.

text
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.

NeedUseCopies
Build a stringstrings.BuilderOnce, while growing
Build bytes, then writebytes.BufferWhile growing
Edit characters[]byte(s) … string(b)Twice
Keep a piece of a big stringstrings.Clone(s[i:j])Once, small
Split/trim bytesbytes.Cut, bytes.Fields, bytes.TrimSpaceNo (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".

text
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 loops

Real 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.

LayoutAllocationsJagged rowsCache-friendly
[R][C]T0–1NoYes
[][]T, row by rowR (+1)YesLess
[][]T over one buffer1 (+1)NoYes
Flat []T + index1NoYes

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).

text
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 table

Real 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 formMissing keyPresent key
v := m[k]zero valuevalue
v, ok := m[k]zero value, falsevalue, true
_, ok := m[k]falsetrue (membership)
nil map readzero 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.

hash(key, seed) = 64 bitsupper bits: tableH1 (57 bits): groupH2 (low 7 bits):stored in control byteDirectory (globalDepth = 2)00011011table (localDepth 1)≤ 1024 slotstable (localDepth 2)≤ 1024 slotstable (localDepth 2)grows/splits aloneOne group = control word + 8 slotsctrl: 8 bytes, one per slot: empty / deleted / H2k,vk,vk,vk,vemptyk,vdelk,vLookup: H1 → first group; compare H2 against all 8 controlbytes at once; check keys only for matches; continue theprobe sequence until a group with an empty slot.Grow when used > 7/8 of slots (maxAvgGroupLoad = 7 of 8).Below 1024: replace table with double capacity.At 1024: split into two tables (incremental growth).Maps of ≤ 8 entries: a single group, no directory.Go 1.23 and earlier: buckets of 8, load factor 6.5, overflow buckets.
text
     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 group

Real 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).

AspectGo ≤ 1.23 (buckets)Go 1.24+ (Swiss tables)
Slot groupingBucket of 8 pairs + tophash bytesGroup of 8 slots + control word (H2)
CollisionsOverflow buckets (chaining)Open addressing, probe sequence over groups
Max load6.5 per bucket (~81%)7/8 (87.5%) per table
GrowthDouble, evacuate incrementallyPer table: double up to 1024, then split
Shrinks after deleteNoNo
Iteration orderRandomised 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").

text
     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 c

Real 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).

OutputOrdered?
for range mNo, 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"].

text
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 reuse

Real 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 typem[k].f = vIn-place updateCost
map[K]T (struct)Compile errorRead, modify, write backCopies the struct twice
map[K]*TAllowedYesOne allocation per value, GC scanning
map[K][]Tm[k][i] = v allowedElements yes, append needs write-backSlice 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.

text
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)             // 0

Real 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 typeAllowedNote
string, ints, boolYesMost common
float64YesNaN never found; -0 == +0
[N]T array, struct of comparable fieldsYesComposite keys without concatenation
Pointer, channelYesIdentity, not content
Interface (any)YesPanics if dynamic type is not comparable
Slice, map, funcNoinvalid 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).

text
     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, correct

Real 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.

OptionTypedGood forCost
map + sync.MutexYesGeneral read/writeAll access serialised
map + sync.RWMutexYesRead-heavy, short critical sectionsRLock overhead under write contention
sync.MapNo (any)Write-once caches, disjoint keysType assertions; no len
Sharded maps (N × mutex+map)YesVery hot countersMore code
One owner goroutine + channelsYesComplex invariantsLatency 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).

text
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 map

Real 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.

FunctionSinceReturns
Clone, Copy1.21New map / nothing
Equal, EqualFunc1.21bool
DeleteFunc1.21nothing (in place)
All, Keys, Values1.23iter.Seq2 / iter.Seq
Insert, Collect1.23nothing / 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.

text
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{})   // false

Real 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.

CompareUsenil vs empty
Arrays==—
Slicesslices.Equal, bytes.EqualEqual
Mapsmaps.EqualEqual
Anything nestedreflect.DeepEqual or go-cmpDifferent

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.

text
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 filling

Real 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.

ElementAllocation per elementGC scanMutation through slice
[]T small structNoneOnly if T has pointerss[i].f = v works
[]T huge struct (KBs)NoneSameCopy on range value variable
[]*TOne eachEvery elementShared 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 ​

ValueWhat the variable holds (64-bit)unsafe.SizeofWhere the elements live
[4]int64The 4 elements themselves32Inline (stack, struct field, or inside another array)
[]int64{array *T, len int, cap int}24Separate backing array (heap, or stack if it does not escape)
string{ptr *byte, len int}16Read-only bytes (static data or heap)
map[K]VPointer to a runtime Map8Directory, tables, groups (heap)
[]T inside a structThe 24-byte header24Shared 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).

MessageKindCauseFix
panic: runtime error: index out of range [3] with length 3Panic (recoverable)s[i] with i >= len(s)Check len, or range
panic: runtime error: slice bounds out of range [:5] with capacity 4Panics[:j] with j > cap(s)Clamp j
panic: runtime error: slice bounds out of range [3:2]Paniclow > highValidate offsets
panic: runtime error: makeslice: len out of rangePanicNegative or huge make lengthValidate sizes from input
panic: runtime error: cannot convert slice with length 2 to array or pointer to array with length 3Panic[3]int(s) with short sCheck len(s) first
panic: assignment to entry in nil mapPanicWrite to var m map[K]Vmake the map
panic: runtime error: hash of unhashable type []intPanicSlice as dynamic key in map[any]VUse a comparable key
fatal error: concurrent map writesFatal, NOT recoverableTwo goroutines writingMutex / sync.Map
fatal error: concurrent map read and map writeFatalReader and writerMutex (RWMutex)
fatal error: concurrent map iteration and map writeFatalrange while another goroutine writesLock, or iterate a snapshot
WARNING: DATA RACERace detector reportUnsynchronised access seen by -raceSame as above; run go test -race in CI
invalid operation: a == b (slice can only be compared to nil)Compile== on slicesslices.Equal
invalid map key type []intCompileSlice/map/func keyArray or struct key
cannot assign to struct field m["a"].X in mapCompileMap elements are not addressableRead-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.Mutexgo vet (copylocks)Struct with mutex passed by valuePass *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.

text
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 ​

ToolWhat it shows hereCommand
Race detectorUnsynchronised map/slice access with both stacksgo test -race ./...
go vetcopylocks (mutex in a copied struct), loopclosure on old codego vet ./...
Escape analysisWhich make/append go to the heapgo build -gcflags=-m ./pkg
Allocation countingAllocations per call in a testtesting.AllocsPerRun(n, f)
Benchmarksns/op, B/op, allocs/opgo test -bench . -benchmem
Heap profileWho retains big arrays (sub-slice leaks)go tool pprof -sample_index=inuse_space heap.out
GOEXPERIMENT=noswissmapOld map implementation (Go 1.24 only; removed later)GOEXPERIMENT=noswissmap go test ./...

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Caller's data overwritten by appendFull slice expressions[a:b:b], slices.ClipNo copyStill shares for writes
Caller keeps or mutates the resultCloneslices.Clone, bytes.CloneFully independentOne allocation + copy
Many reallocationsPreallocatemake([]T, 0, n), slices.GrowOne allocationNeed a size estimate
Big array retainedCopy outbytes.Clone, strings.CloneGC frees the big bufferCopy cost
Filter without allocatingIn places[:0] + append, slices.DeleteFuncZero allocationsDestroys input
null in JSONNormalise[]T{}, map[K]V{} at the boundaryStable contractOne small allocation
Missing vs zeroComma-okv, ok := m[k]ExplicitNone
Struct in map not updatableWrite back or pointersa := m[k]; …; m[k] = aKeeps values compactTwo copies
Shared map across goroutinesLock or sync.MapRWMutex + mapCorrect, typedContention
Non-deterministic outputSort keysslices.Sorted(maps.Keys(m))DeterministicO(n log n)
Equal priorities reorderStable sort or tie-breakerSortStableFunc, cmp.OrPredictableStable is a bit slower
Map memory stays highRebuildmaps.Clone or new map + copyFrees old tablesCopy cost, brief double memory

Arrays as values and keys ​

go
// 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.

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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 ​

go
// 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.

go
// 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.

go
// 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.

go
// 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.

go
// 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.ReadSlice and bytes.Fields return views into existing memory; bytes.Clone, strings.Clone and slices.Clone exist precisely to break that sharing. io.ReadAll returns a fresh slice (Go 1.26 made it "a minimally sized final slice").
  • database/sql and pgx reuse buffers. sql.RawBytes "holds a reference to memory owned by the database itself" and is only valid until the next Next/Scan; scan into []byte (copied) if you keep it. Details in database/sql & pgx.
  • encoding/json reuses what you decode into. Go 1.27's Unmarshal docs: 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 range statement 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
// 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)
PHPGoDifference that bites
$list = [1, 2, 3]s := []int{1, 2, 3}Go slice assignment shares elements; PHP copies on write
$list[] = 4s = 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) / usortslices.Sort / slices.SortFuncPHP 8's sort is stable; Go's SortFunc is not
array_unique($a)slices.Sort + slices.CompactCompact 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 loopNo lazy collection object; iterators (1.23) are the closest
json_encode([]) → []nil slice → nullNormalise nil to empty at the API edge
PHP-FPM: one request per process, no shared arraysGoroutines share memoryA 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 ​

What does the data need?Fixed size, value copyhash digest, RGB, grid→ array [N]T (comparable)Ordered sequence→ slice []Tsize known? make([]T, 0, n)Lookup by key→ map[K]V, make(m, hint)need order? sort the keysReturned sub-slice or long-lived?s[a:b:b] or slices.CloneWriters in many goroutines?yes: mutex (RWMutex) + mapwrite-once cache / disjoint keys: sync.MapElement type:small structs → values ([]T)shared identity or huge → pointers([]*T: one allocation each,GC scans every pointer)
SituationRecommendationExtra techniqueReason
Fixed-size identity (hash, IP, coordinate)Array [N]TUse as map keyComparable, no allocation
Rows from a query, known countmake([]T, 0, n)Value elementsOne allocation
Unknown count, smallvar s []T + append—Growth is cheap at small sizes
Returning part of an internal slices[a:b:b]Document "view"No copy, safe appends
Storing part of a big bufferbytes.Clone / slices.Clone—Avoid retaining the buffer
Filter a slice you ownslices.DeleteFunc—Zero allocations, tail zeroed
Unique sorted valuesslices.Sort + slices.Compactslices.ClipLinear after sort
Membership in a big, static listSorted slice + BinarySearch, or map[K]struct{}—O(log n) and compact vs O(1) and larger
Lookup by IDmap[K]V with make(…, n)Comma-okO(1) average
Deterministic outputslices.Sorted(maps.Keys(m))—Map order is random
Shared map, mixed reads/writesStruct with sync.RWMutex + mapSnapshot for iterationTyped, simple
Write-once cache / disjoint keys per goroutinesync.MapLoadOrStoreFewer lock contentions
JSON array fieldNever nil at the boundary[]T{}[] instead of null
Sort with meaningful tiesslices.SortStableFuncor cmp.Or tie-breakerPredictable order
Matrix / imageFlat []T with strideOr rows over one bufferOne 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.

sql
-- 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[]);
text
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 order

Modular 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.

text
     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× ​

LoadWhat 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.

bash
cd docs/snippets/go/arrays-slices-maps/go
go vet ./... && go test -race ./...

1. Watch append grow.

text
$ 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.

text
$ 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.

text
$ go run ./cmd/lab order
d e a b c
a b c d e
d e a b c

4. nil vs empty in JSON.

text
$ 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.

text
$ 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 writes

6. The race detector on a map (a two-goroutine test written for this lab, not part of the module):

text
$ 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.

text
$ 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/op

8. Escape analysis.

text
$ 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 heap

Common misconceptions ​

BeliefReality
Slices are passed by referenceThe header is passed by value; elements are shared, length and capacity are not
append always copiesOnly when len+n > cap; otherwise it writes into the shared array
Capacity doubles forever2x below 256 elements, then about 1.25x, plus size-class rounding
make([]T, n) reserves roomIt creates n zero elements; use make([]T, 0, n) to reserve
s[a:b:b] copiesIt only caps capacity; writes are still shared
A small sub-slice is small in memoryIt keeps the whole backing array alive
nil slices are dangerouslen, range, append work; only JSON and == nil differ
Maps iterate in insertion orderOrder is unspecified and randomised
fmt.Println(m) proves the order is stablefmt sorts keys for printing since Go 1.12
A concurrent map write is a harmless raceIt is fatal error: concurrent map writes; the process dies
sync.Map is the default concurrent mapIt is for write-once or disjoint-key workloads; a mutex is the default
delete frees map memoryMaps never shrink; rebuild to reclaim
maps.Clone is a deep copyIt is shallow
slices.Compact removes all duplicatesOnly adjacent ones; sort first
slices.SortFunc keeps ties in orderIt is not stable; use SortStableFunc

Cheat sheet ​

TopicWhat to remember
ArrayValue; [N]T; copied on assign; == and map key OK
Slice headerptr, len, cap; 24 bytes; copying it shares elements
makemake([]T, len, cap); make(map[K]V, hint); maps must be made before writing
appendAlways s = append(s, …); shares if it fits, reallocates if not
Growth2x under 256, then += (cap+768)/4, then size class
Sub-slices[a:b] cap = cap(s)-a; use s[a:b:b] to stop spills
copyCopies min(len); never grows dst; overlap OK
Reuses[:0] keeps capacity; clear the tail if it holds pointers
LeaksClone pieces of big buffers you keep
nil vs emptySame behaviour except == nil, reflect, JSON (null vs [])
slicesSort, BinarySearch, Compact (sorted), Delete (zeroes tail 1.22), Insert, Concat, Clone, Grow, Clip
Iteratorsslices.Sorted(maps.Keys(m)), Collect, Values, All, Chunk (views)
Map readMissing key = zero value; v, ok := m[k] to tell apart
Map orderRandom; sort keys for output
Map mutationdelete in range OK; clear(m); struct elements not addressable
Map internalsGo 1.24 Swiss tables: groups of 8, 7/8 load, tables ≤ 1024, split; never shrinks
ConcurrencyReaders only: OK. Any writer: mutex, or sync.Map for its two cases

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
ArrayFixed-length sequence [N]T; a value, copied on assignment
SliceDescriptor (ptr, len, cap) of a contiguous segment of an array
Slice headerThe runtime struct behind a slice: pointer, length, capacity (24 bytes on 64-bit)
LengthNumber of elements a slice exposes; len(s)
CapacityElements 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-sliceA slice made by a slice expression from another slice; shares the backing array
AliasingTwo slices referring to overlapping elements of one array
makeBuilt-in that creates slices, maps and channels
appendBuilt-in that adds elements, reallocating when capacity is exceeded
growsliceRuntime function that allocates the bigger array for append
Growth factorRatio new cap / old cap: 2 below 256 elements, tending to 1.25
Size classAllocator bucket size; capacities are rounded up to fill it
copyBuilt-in copying min(len(dst), len(src)) elements, overlap-safe
Three-index slice / full slice expressions[low:high:max], capacity max-low (Go 1.2)
clearBuilt-in (Go 1.21): zeroes slice elements or deletes all map entries
nil sliceZero-value slice; len 0, encodes as JSON null
Empty sliceNon-nil slice with len 0; encodes as JSON []
JSON nullWhat encoding/json emits for nil slices and maps
Memory leak (sub-slice)A small slice keeping a large backing array reachable
PreallocationCreating a slice/map with its final capacity to avoid regrowth
slices packageGeneric slice helpers (Go 1.21): Sort, BinarySearch, Compact, Clone, Delete, Insert, Concat…
slices.SortIn-place pdqsort for ordered types; not stable
slices.BinarySearchO(log n) search in a sorted slice; returns index and found
slices.CompactRemoves consecutive duplicates
slices.CloneShallow copy of a slice
slices.DeleteRemoves s[i:j]; zeroes the vacated tail since Go 1.22
slices.InsertInserts values at an index, may reallocate
slices.ConcatJoins slices in one allocation (Go 1.22)
slices.CollectBuilds a slice from an iterator (Go 1.23)
slices.ValuesIterator over a slice's elements (Go 1.23)
slices.EqualElement-wise equality; nil equals empty
slices.Grow / slices.ClipEnsure spare capacity / remove it
Iterator (iter.Seq)A function you can range over (Go 1.23)
Stable sortSort that keeps the input order of equal elements
pdqsortPattern-defeating quicksort used by slices.Sort
bytes package[]byte counterparts of strings functions, plus Buffer
strings.BuilderEfficient string construction without a final copy
Multi-dimensionalArrays of arrays, slices of slices, or flat slices with an index formula
MapBuilt-in hash map map[K]V; unordered
Hash map / hash tableStructure that finds values by hashing keys
BucketPre-1.24 map storage unit: 8 key/value pairs plus overflow pointer
Swiss tableOpen-addressing hash table design used by Go maps since 1.24
Group / control word8 slots plus 8 bytes of H2 fingerprints in a Swiss table
H1 / H2Upper 57 bits (probe position) and lower 7 bits (fingerprint) of the hash
Load factorUsed slots / total slots; 7/8 triggers growth in Go 1.24+ maps, 6.5 per bucket before
Extendible hashingDirectory of tables selected by hash bits; lets one table split alone
Iteration orderUnspecified and randomised for maps
Make with hintmake(map[K]V, n): preallocates for about n entries
deleteBuilt-in removing one map entry; no-op if missing
Comma-okv, ok := m[k] form telling missing from zero
Zero valueDefault value of a type, returned for missing map keys
Not addressableMap elements cannot have their address taken or fields assigned
Concurrent map writesFatal runtime error when goroutines write a map without synchronisation
sync.MapConcurrent map for write-once or disjoint-key workloads
maps packageGeneric map helpers (Go 1.21; iterators 1.23)
maps.KeysIterator over a map's keys (Go 1.23)
maps.CloneShallow copy of a map
NaN keyFloat key that never equals itself; insertable, never findable
Ordered hash mapPHP's array: hash map that remembers insertion order
Escape analysisCompiler 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.

Built by Morteza Negahi