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.

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]intand[4]intare 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. lenis what you may index;capis how farappendcan grow before reallocating.appendwrites in place whenlen < capand 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 withs; the result's capacity runs to the end of the original array's capacity unless a three-index forms[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;copyis the only way to move elements between two slices safely when they may overlap.
Basic syntax and type signatures
// 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
| Operation | Copies data | Shares storage | Can reallocate | Length after |
|---|---|---|---|---|
b := a (array) | yes, whole array | no | no | 3 |
t := s (slice) | header only | yes | no | unchanged |
s[i:j] | no | yes | no | j - i, cap to array end |
s[i:j:k] | no | yes | no | j - i, cap k - i |
append(s, v) | only when len == cap | yes until growth | yes | len + 1 |
append(s, w...) | same rule, per element | yes until growth | possible | len + len(w) |
copy(dst, src) | yes, min(len) elements | no | no | len(dst) |
slices.Clone(s) | yes, exact length | no | no | len(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
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
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
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
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
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 symptom | Cause | Fix |
|---|---|---|
first argument to append must be a slice; have *[]T | *[]T passed instead of []T | use append(*p, v) and assign back, or pass the slice |
append result ignored, slice unchanged | new header discarded | s = append(s, v) |
index out of range [n] with length n | indexing at len, which is one past the last element | append, or size with len+1 |
cannot use a (variable of type [3]int) as []int value | array passed where a slice is expected | pass a[:] |
| Another slice changes unexpectedly | two slices alias one backing array | copy at the boundary, or use s[i:j:k] |
copy(dst, src) copies nothing | destination has length 0 but capacity | dst = dst[:n] before copy, or append |
Data disappears after append grows | old array still referenced by another slice | copy before mutating shared storage |
| Memory not released after removing elements | stale pointers remain in the array beyond len | zero 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 toolsSmall utilities that fit Go work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Go guides
All Go guidesGo iota: Enumerations, Bitmask Flags, and Constant Expressions
How iota advances per const line, typed enums with gaps, bit flags with 1 << iota, and the unit scale pattern that shifts with one blank line.
Go JSON: Marshaling, Unmarshaling, Struct Tags, and Custom Parsers
Struct tags, omitempty that skips false and zero, custom marshalers without recursion, RawMessage for tagged unions, and float64 precision loss.
Go Strings, Runes, and Bytes: UTF-8 Encoding, Conversion, and Memory
Bytes versus runes, len that counts bytes, slicing that splits characters, Builder for linear concatenation, and normalization the standard library omits.
Go select Statement: Non-Blocking Operations, Timeouts, and Nil Channels
Random choice among ready cases, non-blocking polls with default, nil channels that disable a case, timer reuse, and labeled breaks out of a loop.
More in Go
All Go guidesThe guides filed next to this one in Go, in library order.