Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Go Slices vs Arrays: Slice Header, Length, Capacity, and append Mechanics

The three-word slice header, why append sometimes writes into another slice's memory, how the three-index slice prevents it, and where capacity hints and clearing matter.

~5 min readGo
#Go#Data Structures#Memory
3D illustration of a three-word slice header pointing into a contiguous memory array that expands when capacity is exceeded

A slice in Go is a three-word header — pointer, length, capacity — that describes a view into an array. An array is the storage itself, with a fixed size that is part of its type. Almost every surprise in Go's collection code comes from that split: assignment copies the header and shares the array, append may or may not copy it, and two slices can alias the same memory while having different lengths and capacities.

Quick Summary

  • An array's size is part of its type: [3]int and [4]int are different types, and an array is copied on assignment.
  • A slice is struct{ array *T; len, cap int } conceptually; copying a slice copies only the header, so both copies share the backing array.
  • len is what you may index; cap is how far append can grow before reallocating.
  • append writes in place when len < cap and allocates a new array when it must grow, so the returned slice must always be assigned: s = append(s, v).
  • s[i:j] shares storage with s; the result's capacity runs to the end of the original array's capacity unless a three-index form s[i:j:k] caps it.
  • Growing a slice allocates a new array and copies; the old array stays valid for any slices still pointing at it, so writes after growth diverge silently.
  • make([]T, 0, n) when the size is known avoids repeated reallocation; copy is the only way to move elements between two slices safely when they may overlap.

Basic syntax and type signatures

go
// Array: fixed size, part of the type. var a [3]int // [3]int, zero-valued b := [3]int{1, 2, 3} c := [...]int{1, 2, 3} // inferred length, not a slice // Slice: header + backing array. s := []int{1, 2, 3} // len 3, cap 3 t := make([]int, 2, 8) // len 2, cap 8 u := make([]int, 8) // len 8, cap 8 // Slicing shares storage. head := s[:2] // len 2, cap 3 tail := s[1:] // len 2, cap 2 full := s[0:1:2] // len 1, cap 2 (three-index slice) // append returns a possibly new header. s = append(s, 4) // copy is bounded by the shorter length. n := copy(t, s) // n = min(len(t), len(s))

s[:2] and s[1:] both point into the same three-element array. Writing through head changes s[0]; appending to tail overwrites s[2] if capacity allows, because tail's capacity reaches the end of the backing array.

Comparison

OperationCopies dataShares storageCan reallocateLength after
b := a (array)yes, whole arraynono3
t := s (slice)header onlyyesnounchanged
s[i:j]noyesnoj - i, cap to array end
s[i:j:k]noyesnoj - i, cap k - i
append(s, v)only when len == capyes until growthyeslen + 1
append(s, w...)same rule, per elementyes until growthpossiblelen + len(w)
copy(dst, src)yes, min(len) elementsnonolen(dst)
slices.Clone(s)yes, exact lengthnonolen(s)

The important asymmetry is between append and copy: append may grow and never writes past the source's length in the caller's view, while copy writes into the destination's existing length and refuses to grow it.

Practical edge cases and deep dives

1. Aliasing through a sub-slice, and the three-index fix

go
func badPrefix(s []int) []int { return s[:2] // cap extends over the rest of s } func goodPrefix(s []int) []int { return s[:2:2] // cap == len, so append must allocate } func main() { base := []int{1, 2, 3, 4} p := badPrefix(base) p = append(p, 99) fmt.Println(base) // [1 2 99 4] — the caller's data changed fmt.Println(p) // [1 2 99] q := goodPrefix(base) q = append(q, 42) fmt.Println(base) // [1 2 99 4] — unchanged fmt.Println(q) // [1 2 42] }

badPrefix hands out a slice whose capacity reaches into storage the caller still owns, so a later append writes into it. The three-index form sets capacity to the visible length, which forces append to allocate and makes the returned slice safe to grow. Returning sub-slices of caller data is the single most common source of "why did my slice change" bugs in Go.

2. Sharing an array through a struct field and the append trap

go
type Buffer struct { data []byte } func (b *Buffer) Write(p []byte) { b.data = append(b.data, p...) } func (b *Buffer) Bytes() []byte { return b.data // caller can keep the reference and observe later writes } func (b *Buffer) SafeBytes() []byte { return slices.Clone(b.data) // caller gets a copy, at the cost of an allocation } func demo() { var b Buffer b.Write([]byte("hello")) view := b.Bytes() b.Write([]byte(" world")) fmt.Println(string(view)) // "hello world" — view grew with the buffer }

view is a header onto the same array, so it sees everything appended as long as no reallocation happened; after a reallocation it silently stops seeing new writes while b.data continues. Returning slices.Clone or a copy with append([]byte(nil), b.data...) fixes it at the cost of an allocation per call, which is the honest trade-off for an exported accessor.

3. make with capacity and the growth curve

go
func collect(ids []string) []int { out := make([]int, 0, len(ids)) // one allocation for _, id := range ids { out = append(out, len(id)) } return out }

Without the capacity hint, append grows the array repeatedly; Go's runtime increases capacity by roughly 2× for small slices and closer to 1.25× above a threshold, so building an n-element slice without a hint costs O(log n) reallocations and copies. The capacity hint is the cheapest optimization in Go and the correct default whenever the final length is known. Note that make([]T, n) and make([]T, 0, n) are not interchangeable: the first has length n and appending writes at index n, the second appends at index 0.

4. Deleting from the middle without leaking or aliasing

go
func removeAt[T any](s []T, i int) []T { if i < 0 || i >= len(s) { return s } copy(s[i:], s[i+1:]) var zero T s[len(s)-1] = zero // clear the last slot so the element can be collected return s[:len(s)-1] } func orderedRemove[T any](s []T, i int) []T { last := len(s) - 1 s[i] = s[last] var zero T s[last] = zero return s[:last] } func filterInPlace[T any](s []T, keep func(T) bool) []T { out := s[:0] // reuse s's storage for _, v := range s { if keep(v) { out = append(out, v) } } // clear the tail beyond the new length var zero T for i := len(out); i < len(s); i++ { s[i] = zero } return out }

removeAt preserves order in O(n) moves; orderedRemove is O(1) but reorders. Both clear the vacated slot, which matters when T holds pointers: the array keeps every slot up to its capacity alive, so a stale pointer prevents garbage collection of the object it referenced. filterInPlace is the standard in-place filter; writing to s[:0] while ranging over s is safe because the write index never passes the read index.

5. Slices as map values do not grow in place

go
m := map[string][]int{"a": {1, 2, 3}} // This compiles only because `m["a"]` is addressable in this statement; // the assignment writes the new header back into the map. m["a"] = append(m["a"], 4) // But this does not modify the map's slice at all: func wrongAppend(m map[string][]int) { s := m["a"] _ = append(s, 99) // result discarded: the map still holds the old header }

A map value is copied out on read, so append grows the local header while the map keeps the old one — the element is lost. The fix is the explicit write-back m[k] = append(m[k], v). The same reasoning explains why a map of structs cannot have its fields modified in place: m[k].Field = x does not compile, and the fix is either a pointer value or a read-modify-write.

Common mistakes and compiler errors

Error or symptomCauseFix
first argument to append must be a slice; have *[]T*[]T passed instead of []Tuse append(*p, v) and assign back, or pass the slice
append result ignored, slice unchangednew header discardeds = append(s, v)
index out of range [n] with length nindexing at len, which is one past the last elementappend, or size with len+1
cannot use a (variable of type [3]int) as []int valuearray passed where a slice is expectedpass a[:]
Another slice changes unexpectedlytwo slices alias one backing arraycopy at the boundary, or use s[i:j:k]
copy(dst, src) copies nothingdestination has length 0 but capacitydst = dst[:n] before copy, or append
Data disappears after append growsold array still referenced by another slicecopy before mutating shared storage
Memory not released after removing elementsstale pointers remain in the array beyond lenzero the freed slots

Two rules cover most of the list. Always treat a slice as a borrowed view that someone else may also hold, and copy at the point where ownership changes hands. And always remember that len is what you can read while cap is what another append can overwrite, which is the reason the three-index slice exists and the reason a function returning a sub-slice of its input should cap it.

Try matching browser tools

All tools

Small utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Go guides

More in Go

All Go guides

The guides filed next to this one in Go, in library order.