Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 147 ยท Collections

How Slices Work: Length, Capacity and Aliasing

Understand the Go slice header, how append grows capacity, why slices share memory and cause surprising bugs, full slice expressions, memory leaks from reslicing, and how to preallocate.

Slices are easy to use and subtle to understand. Most "weird" slice bugs in Go, such as a value that changes behind your back or an append that seems to work only sometimes, come from one fact: a slice is not the data, it is a small description of a piece of an array. Once you can picture that description, the behavior becomes predictable.

This lesson builds on Slices. You'll look at the slice header, watch append grow capacity, see how two slices can alias the same memory, learn the full slice expression that prevents it, and finish with two practical topics: memory leaks caused by reslicing, and preallocation for speed.

The slice header

A slice value is a tiny struct with three fields:

Go
type sliceHeader struct {
	Data *T   // pointer to the first element the slice can see
	Len  int  // number of elements you can index
	Cap  int  // elements from Data to the end of the backing array
}

You can't write this type yourself (the runtime owns it), but the model is exact. The elements live in a separate backing array. When you assign a slice, pass it to a function or reslice it, only the three-word header is copied. The backing array is shared.

Go Two headers, one backing array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

cap(b) is 4, not 3, because capacity is measured from where the slice starts to the end of the backing array. The slice b can't see a[0], since there is no way to reslice backwards past the start.

How append grows a slice

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

  1. If len(s) < cap(s), there is spare room: it writes x into the backing array right after the last element and returns a header with Len increased by one. No allocation, and the same backing array.
  2. If the slice is full, it allocates a new, larger array, copies the existing elements over, adds x, and returns a header pointing at the new array.

The growth factor is an implementation detail that has changed between releases, but the shape has been stable for years: small slices roughly double, and large slices grow by a smaller factor (about 1.25x) so that memory use doesn't explode. The exact numbers can differ by element size, because Go rounds allocations up to its internal size classes. Watch the pattern:

Go Watching capacity change

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Each printed line is a reallocation. Do not hard-code these numbers into your programs or your tests: they are what this compiler version does today, not a promise. What is guaranteed is that append gives you amortized constant time per element.

You can ask for capacity yourself. slices.Grow(s, n) guarantees room for n more elements, and slices.Clip(s) trims the capacity down to the length. Both come from the slices package.

Why you must keep the result of append

Because append may or may not allocate, the slice you pass in and the slice you get back may or may not share memory. This example shows both outcomes:

Go append sometimes reallocates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The same code behaves differently depending on spare capacity. That is the reason Go style says: after append, use only the returned slice (s = append(s, x)), and never keep using the old one as if the two were independent.

Aliasing surprises

When several slices overlap, append through one can silently overwrite data seen through another. This is the classic puzzle:

Go append overwrites a neighbor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

head had room for three elements in the shared array, so append wrote 99 into nums[2] instead of allocating. Nothing is wrong with Go here. A slice is a window, and appending to a window writes to the array behind it.

A second trap appears in functions that build and return sub-slices of a shared buffer. If two callers each append to their own sub-slice, they can overwrite each other.

Full slice expressions

The cure is the full slice expression s[low:high:max]. It sets the capacity of the result to max - low, so the new slice can't reach past max. Appending beyond that is forced to allocate:

Go Limiting capacity with s[low:high:max]

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The rule is 0 <= low <= high <= max <= cap(original). Use s[:n:n] whenever you hand out a piece of a buffer that others might append to. The standard library does this in many places.

Memory leaks from reslicing

Because a sub-slice keeps the whole backing array alive, a tiny slice can pin a huge array in memory. Imagine reading a 100 MB file and keeping only the first 10 bytes:

Go
func header(path string) []byte {
	data, _ := os.ReadFile(path) // 100 MB backing array
	return data[:10]             // keeps all 100 MB alive!
}

The garbage collector can't free the array while any slice still points into it. The fix is to copy the part you need into a fresh, right-sized slice, so the big array becomes garbage:

Go Copy small pieces out of big arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The same issue applies to slices of pointers. When you remove elements from the end or start of a slice of pointers, the dropped pointers stay in the backing array until something overwrites them, which keeps the objects they point to alive. Set removed slots to nil before shrinking:

Go
last := len(items) - 1
items[last] = nil          // let the GC reclaim it
items = items[:last]

slices.Delete (since Go 1.22) does this clearing for you, and so does clear on the tail. See garbage collection for how the collector decides what is reachable.

Preallocating for speed

Every reallocation allocates, copies and leaves garbage. If you know roughly how many elements you will add, ask for the capacity up front:

Go Preallocation saves allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

testing.AllocsPerRun counts heap allocations per call, which is far steadier than timing. The preallocated version reports 0 because the compiler can keep a slice of this constant, modest size on the stack, so nothing reaches the heap at all. We print a comparison for the growing version instead of its exact count, because that depends on the Go release. For a program you care about, measure with a real benchmark; see benchmarks.

A common pattern is converting one slice into another:

Go
out := make([]string, 0, len(users))
for _, u := range users {
	out = append(out, u.Name)
}

Allocating with len (not 0) and then assigning out[i] = ... also works and is equally fast. Pick make(..., 0, n) with append when some items may be skipped.

A range loop sees the original length

One last aliasing detail. for range s evaluates s once, before the loop starts, so appending inside the loop does not make the loop longer:

Go range evaluates the slice once

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The index loop here is capped at five iterations on purpose; without the cap it would run forever, since the slice grows as fast as the index does.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which three fields make up a slice header?

    A slice is a pointer to the first visible element plus the length and capacity. Copying a slice copies only these three words.
  2. 2. What does this print? a := []int{1, 2, 3, 4}; b := a[:2]; b = append(b, 9); fmt.Println(a)

    b has capacity 4, so append writes 9 into the shared backing array at index 2, which is a[2].
  3. 3. What is cap(s) for s := make([]int, 0, 10)[3:5]?

    Capacity is counted from the start of the slice to the end of the backing array: 10 - 3 = 7.
  4. 4. How does nums[:2:2] differ from nums[:2]?

    The third index limits capacity (max - low). With no spare room, append reallocates and cannot overwrite the original data.
  5. 5. Why can returning big[:10] from a function waste memory?

    As long as the sub-slice is alive, the whole backing array stays reachable. Copy the part you need with slices.Clone or copy.

Summary

  • A slice is a header of pointer, length and capacity. Copies of a slice share the same backing array.
  • append reuses the array when there is spare capacity and allocates a larger one when there is not. The growth rule is an implementation detail.
  • Always continue with the slice returned by append.
  • Overlapping slices alias each other: writes through one are visible through the others, including writes made by append.
  • Use s[low:high:max] to cap capacity and stop a sub-slice from overwriting its neighbors.
  • A small sub-slice keeps its whole backing array alive. Copy out what you need, and nil out dropped pointer elements.
  • Preallocate with make([]T, 0, n) or slices.Grow when the size is known.
  • range evaluates the slice once, before the loop.

Next: Maps covers Go's built-in hash table for looking up values by key.