Go Slices vs Arrays: A Deep Dive
Arrays are values, slices are windows. How Go slices really work: the ptr/len/cap header, why append can overwrite your data, how slices grow, and when an array is the better choice.
#go #golang #slices #backend
Arrays and slices look almost the same in Go code. Under the hood they behave very differently, and most "why did my data change?" bugs live in that gap.
TL;DR
- An array is a fixed-size value. Its length is part of its type:
[3]intand[4]intare different types. Assigning or passing it copies every element. - A slice is a small struct of three words: pointer, length, capacity. It's a window onto an array. Copying a slice copies the window, not the data.
appendwrites into the existing array if there is room incap, and only allocates a new one when there isn't. That is why two slices can silently overwrite each other.- Always use the result of
append:s = append(s, x). - Use the full slice expression
s[low:high:max]to stop anappendfrom writing into memory you don't own. - If you know the size,
make([]T, 0, n). On my machine that was 19 allocations → 1 and about 3× faster.
All the output below is real, run on Go 1.27.4.
Arrays: fixed size, value semantics
a := [3]int{1, 2, 3}
b := [4]int{1, 2, 3, 4}
fmt.Printf("%T %T\n", a, b)
fmt.Println(len(a), len(b))
c := a // full copy
c[0] = 99
fmt.Println(a, c)
fmt.Println(a == [3]int{1, 2, 3})
[3]int [4]int
3 4
[1 2 3] [99 2 3]
true
Three things to notice:
- The length is part of the type. You can't pass a
[4]intto a function that takes[3]int. That's why arrays rarely show up in function signatures. - Assignment copies.
c := acopies all three ints. Changingcnever touchesa. This is the same as assigning a struct. - Arrays are comparable with
==(if their element type is), so they can be map keys. Slices can't.
a (24 bytes of ints)
0
1
1
2
2
3
b (its own copy)
0
1
1
2
2
3
Press play to assign and write.
Passing arrays to functions
func double(arr [3]int) { arr[0] *= 2 }
func doublePtr(arr *[3]int) { arr[0] *= 2 }
func doubleSlice(s []int) { s[0] *= 2 }
a := [3]int{1, 2, 3}
double(a)
fmt.Println(a) // [1 2 3] the function got a copy
doublePtr(&a)
fmt.Println(a) // [2 2 3]
s := []int{1, 2, 3}
doubleSlice(s)
fmt.Println(s) // [2 2 3] same underlying array
Go passes everything by value. For an array, "the value" is all the elements. For a slice, "the value" is just the three-word header. Look at the sizes:
var big [1024]int
var sl []int
fmt.Println(unsafe.Sizeof(big), unsafe.Sizeof(sl))
8192 24
Passing big copies 8 KB. Passing any slice copies 24 bytes (on 64-bit), no matter how many elements it points to.
Slices: a header over an array
The runtime defines a slice like this (runtime/slice.go):
type slice struct {
array unsafe.Pointer // first element the slice can see
len int // how many elements you can index
cap int // how many elements exist from array to the end of the backing array
}
A slice never owns memory on its own. There is always a backing array somewhere. Slicing creates a new header pointing into it:
arr := [6]int{10, 20, 30, 40, 50, 60}
s := arr[1:4]
fmt.Println(s, len(s), cap(s))
s[0] = 99
fmt.Println(arr)
t := s[:cap(s)]
fmt.Println(t, len(t), cap(t))
[20 30 40] 3 5
[10 99 30 40 50 60]
[99 30 40 50 60] 5 5
lenishigh - low= 3.capis fromlowto the end of the array = 5, not tohigh.- Writing
s[0]wrotearr[1]. Same memory. - You can re-slice up to
cap, even past the originalhigh.s"can see" 50 and 60 even though they aren't ins.
Play with it. Move low and high, then turn on the 3-index form:
arr [6]int (the backing array)
0
10
1
20
2
30
3
40
4
50
5
60
s := arr[1:4]
s = [20 30 40] · solid = len, dashed = room left in cap
append: the source of most slice bugs
append(s, x) does one of two things:
len < cap: writexinto the backing array at indexlen, return a header withlen+1. No allocation. The array is shared.len == cap: allocate a bigger array, copy the elements, writex, return a header pointing to the new array.
Case 1 is fast, and also the dangerous one:
arr := [6]int{10, 20, 30, 40, 50, 60}
s := arr[1:3] // [20 30], cap 5
s = append(s, 99)
fmt.Println(arr)
[10 20 30 99 50 60]
40 is gone. s had room in its capacity, so append wrote into arr[3], which someone else may still be using. In real code this looks like taking users[:2] to "get the first two", appending a new user to it, and corrupting users[2].
The fix: the full slice expression
s[low:high:max] sets cap to max - low. With max == high, there is no spare room, so the next append must copy:
full := arr[1:3:3] // cap 2
full = append(full, 77)
fmt.Println(arr) // unchanged
fmt.Println(full) // new backing array
[10 20 30 99 50 60]
[20 30 77]
Run both versions:
arr
0
10
1
20
2
30
3
40
4
50
5
60
cap is 5: arr[3..5] is free room as far as s knows.
Use the 3-index form whenever you hand out a sub-slice of something you still own (a buffer, a pool, a parsed message).
Always assign the result of append
func addItem(s []int) { s = append(s, 4) }
func addItemFixed(s []int) []int { return append(s, 4) }
s := make([]int, 3, 10)
addItem(s)
fmt.Println(s, len(s))
fmt.Println(s[:4])
s = addItemFixed(s)
fmt.Println(s)
[0 0 0] 3
[0 0 0 4]
[0 0 0 4]
This one is sneaky. addItem did write the 4 into the shared array (there was room, cap 10). But it changed the len on its own copy of the header. The caller's s still has len 3, so the 4 is invisible, until you re-slice and find it sitting there.
Rule: a function that appends must return the slice (like append itself does), or take a *[]T.
How slices grow
When append runs out of capacity it allocates a larger array. Watching cap while appending 2,000 ints:
var s []int
prev := -1
for i := 0; i < 2000; i++ {
s = append(s, i)
if cap(s) != prev {
fmt.Print(cap(s), " ")
prev = cap(s)
}
}
4 8 16 32 64 128 256 512 848 1280 1792 2560
- Small slices double.
- After 256 elements the growth factor drops smoothly towards 1.25× (
512 → 848 → 1280 …), so big slices don't waste half their memory. - The exact numbers are then rounded up to the allocator's size classes, which is why you see 848 and not 832.
- Go 1.27 starts small: the first
appendto a nil[]intgivescap 4, and a nil[]bytegivescap 32. Older versions gave 1 and 8. Don't write code that depends on these numbers; they change between releases.
Every growth step is an allocation plus a copy of everything so far. If you know the final size, tell Go up front:
func BenchmarkAppendGrow(b *testing.B) {
for b.Loop() {
var s []int
for i := range 10_000 {
s = append(s, i)
}
}
}
func BenchmarkAppendPrealloc(b *testing.B) {
for b.Loop() {
s := make([]int, 0, 10_000)
for i := range 10_000 {
s = append(s, i)
}
}
}
| Benchmark | Time / op | Memory / op | Allocs / op |
|---|---|---|---|
| grow from nil | ~50 µs | 357,626 B | 19 |
make([]int, 0, n) | ~17 µs | 81,920 B | 1 |
(Go 1.27.4, 20-core homelab box, -count 3. Your numbers will differ; the ratio is the point.)
Note make([]int, 0, n) (length 0, capacity n), not make([]int, n). The second gives you n zeros, and append adds after them.
nil slice vs empty slice
var a []int // nil slice
b := []int{} // empty, non-nil
fmt.Println(a == nil, b == nil, len(a), len(b))
ja, _ := json.Marshal(a)
jb, _ := json.Marshal(b)
fmt.Println(string(ja), string(jb))
true false 0 0
null []
For almost everything (len, range, append) they behave the same, and a nil slice is the idiomatic zero value. The one place it matters is JSON: a nil slice encodes as null, an empty one as []. If your API clients expect an array, initialize it.
Converting and copying
s := []int{1, 2, 3, 4}
arr := [4]int(s) // copy into an array (Go 1.20+), panics if len(s) < 4
p := (*[2]int)(s) // pointer to the first 2 elements, shares memory
p[0] = 100
fmt.Println(s, arr)
c := slices.Clone(s) // independent copy
c[1] = 0
fmt.Println(s, c)
[100 2 3 4] [1 2 3 4]
[100 2 3 4] [100 0 3 4]
- Slice → array copies. Slice → array pointer shares.
- To get a slice that is truly yours,
slices.Clone(s)(orappend([]T(nil), s...), orcopyinto amaked slice).
Memory gotcha: a small slice can pin a big array
func firstLine(file []byte) []byte {
i := bytes.IndexByte(file, '\n')
return file[:i] // keeps the WHOLE file alive
}
As long as the returned slice is alive, its pointer keeps the entire backing array reachable, so the garbage collector can't free the 50 MB file you read. Return bytes.Clone(file[:i]) instead when the result outlives the input.
Where arrays still win
Slices are the default. Reach for an array when:
- The size is part of the meaning:
[32]bytefor a SHA-256 hash,[4]bytefor an IPv4 address,[16]bytefor a UUID. - You need a comparable value: as a map key (
map[[2]int]string) or with==. - You want a real copy on assignment: small fixed buffers in structs, value types that should never alias.
- Performance in hot paths: a small array has no header, no separate allocation, and often stays on the stack.
Cheat sheet
Array [N]T | Slice []T | |
|---|---|---|
| Size | fixed, part of the type | dynamic, len and cap |
| What is it | the elements themselves | pointer + len + cap (24 bytes) |
| Assign / pass | copies all elements | copies the header, shares data |
Comparable (==, map key) | yes | no (only == nil) |
| Zero value | N zero elements | nil |
| Grow | never | append (may reallocate) |
| Typical use | hashes, IDs, fixed buffers | everything else |
Summary
- An array is its data. A slice points at data.
lenis what you can read;capis whatappendis allowed to overwrite.appendshares memory until it runs out of capacity. Uses[low:high:max]orslices.Clonewhen you hand out slices you don't want written into.- Always
s = append(s, …), and return the slice from functions that append. - Preallocate with
make([]T, 0, n)when you know the size.
References: Go Slices: usage and internals · Arrays, slices (and strings): the mechanics of append · Go spec: slice expressions · runtime/slice.go
