Blog
Tech11 min read

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]int and [4]int are 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.
  • append writes into the existing array if there is room in cap, 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 an append from 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

go
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})
text
[3]int [4]int
3 4
[1 2 3] [99 2 3]
true

Three things to notice:

  1. The length is part of the type. You can't pass a [4]int to a function that takes [3]int. That's why arrays rarely show up in function signatures.
  2. Assignment copies. c := a copies all three ints. Changing c never touches a. This is the same as assigning a struct.
  3. Arrays are comparable with == (if their element type is), so they can be map keys. Slices can't.
b := a

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.

arrays copy the data, slices copy the window

Passing arrays to functions

go
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:

go
var big [1024]int
var sl []int
fmt.Println(unsafe.Sizeof(big), unsafe.Sizeof(sl))
text
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):

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:

go
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))
text
[20 30 40] 3 5
[10 99 30 40 50 60]
[99 30 40 50 60] 5 5
  • len is high - low = 3.
  • cap is from low to the end of the array = 5, not to high.
  • Writing s[0] wrote arr[1]. Same memory.
  • You can re-slice up to cap, even past the original high. s "can see" 50 and 60 even though they aren't in s.

Play with it. Move low and high, then turn on the 3-index form:

arr[low:high:max]
low1
high4

arr [6]int (the backing array)

0

10

1

20

2

30

3

40

4

50

5

60

s := arr[1:4]

sptr &arr[1]len 3cap 5

s = [20 30 40] · solid = len, dashed = room left in cap

len is what you can read, cap is what append can write

append: the source of most slice bugs

append(s, x) does one of two things:

  1. len < cap: write x into the backing array at index len, return a header with len+1. No allocation. The array is shared.
  2. len == cap: allocate a bigger array, copy the elements, write x, return a header pointing to the new array.

Case 1 is fast, and also the dangerous one:

go
arr := [6]int{10, 20, 30, 40, 50, 60}
s := arr[1:3] // [20 30], cap 5
s = append(s, 99)
fmt.Println(arr)
text
[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:

go
full := arr[1:3:3] // cap 2
full = append(full, 77)
fmt.Println(arr)  // unchanged
fmt.Println(full) // new backing array
text
[10 20 30 99 50 60]
[20 30 77]

Run both versions:

append(s, 99)

arr

0

10

1

20

2

30

3

40

4

50

5

60

sptr &arr[1]len 2cap 5

cap is 5: arr[3..5] is free room as far as s knows.

room in cap = shared memory

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

go
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)
text
[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:

go
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)
	}
}
text
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 append to a nil []int gives cap 4, and a nil []byte gives cap 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:

go
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)
		}
	}
}
BenchmarkTime / opMemory / opAllocs / op
grow from nil~50 µs357,626 B19
make([]int, 0, n)~17 µs81,920 B1

(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

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

go
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)
text
[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) (or append([]T(nil), s...), or copy into a maked slice).

Memory gotcha: a small slice can pin a big array

go
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]byte for a SHA-256 hash, [4]byte for an IPv4 address, [16]byte for 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]TSlice []T
Sizefixed, part of the typedynamic, len and cap
What is itthe elements themselvespointer + len + cap (24 bytes)
Assign / passcopies all elementscopies the header, shares data
Comparable (==, map key)yesno (only == nil)
Zero valueN zero elementsnil
Growneverappend (may reallocate)
Typical usehashes, IDs, fixed bufferseverything else

Summary

  • An array is its data. A slice points at data.
  • len is what you can read; cap is what append is allowed to overwrite.
  • append shares memory until it runs out of capacity. Use s[low:high:max] or slices.Clone when 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

Share To Friends