Slices: The Expandable Filing Cabinet

Slices: The Expandable Filing Cabinet in Go: Picture a records office with a long bank of filing cabinets.

The Analogy: The Label Card on the Drawer

Picture a records office with a long bank of filing cabinets. The folders live in the drawers, but nobody carries drawers around. What people carry is a label card, and every label card says exactly three things: which drawer this section starts at, how many folders are currently filed in it, and how many folders the drawer can physically hold before it is full. Three facts on a small card, and the card is not the folders.

A Go slice is that card, and it really is three words wide: a pointer to an array, a length, and a capacity. This is why passing a slice to a function is cheap no matter how much data it describes, and it is also why the phrase "slices are passed by reference" is wrong in a way that will eventually cost you an afternoon. The card is copied. The folders are not. The function gets its own card pointing at your drawer, so it can rewrite folder three and you will see the change, but if it writes a new card, you never see that.

Filing a new folder is where the analogy earns its keep. The clerk looks at the card, sees there is room in the drawer, drops the folder in the next free slot, and hands you back a card whose length has gone up by one. Everyone else's card still describes the same drawer, so they see the new folder too, whether or not they wanted to. But if the drawer is full, the clerk does something completely different: he requisitions a bigger cabinet, moves every folder across, files the new one, and hands you a card pointing at the new cabinet. Your card and everybody else's now describe two different sets of folders that happen to have started out identical.

That single branch, room in the drawer versus no room in the drawer, is the source of nearly every slice bug in production Go. append may mutate data that other slices can see, or it may quietly stop sharing, and which one happens depends on a capacity you probably did not check. The rest of this lesson is about reading the three numbers on the card, knowing when append crosses that line, and the two or three habits that make the whole category of bug go away.


Syntax or Core Structure

Read the len and cap columns first, then watch arr change under the first append and stop changing under the second.

package main

import "fmt"

func describe(label string, s []int) {
    fmt.Printf("%-9s %v len=%d cap=%d nil=%t\n",
        label, s, len(s), cap(s), s == nil)
}

func main() {
    var nilSlice []int
    empty := []int{}
    made := make([]int, 3, 8)

    describe("nil:", nilSlice)
    describe("empty:", empty)
    describe("made:", made)

    arr := [5]int{1, 2, 3, 4, 5}
    window := arr[1:3] // starts at index 1, holds 2, drawer has room for 4
    describe("window:", window)

    grown := append(window, 99) // room in the drawer
    describe("grown:", grown)
    fmt.Printf("%-18s %v\n", "arr is now:", arr)
    fmt.Printf("%-18s %t\n", "grown aliases arr:", &grown[0] == &arr[1])

    full := append(grown, 100, 200) // no room, so a bigger cabinet
    fmt.Printf("%-18s %v len=%d\n", "full is:", full, len(full))
    fmt.Printf("%-18s %v\n", "arr is still:", arr)
    fmt.Printf("%-18s %t\n", "full aliases arr:", &full[0] == &arr[1])
}

Output:

nil:      [] len=0 cap=0 nil=true
empty:    [] len=0 cap=0 nil=false
made:     [0 0 0] len=3 cap=8 nil=false
window:   [2 3] len=2 cap=4 nil=false
grown:    [2 3 99] len=3 cap=4 nil=false
arr is now:        [1 2 3 99 5]
grown aliases arr: true
full is:           [2 3 99 100 200] len=5
arr is still:      [1 2 3 99 5]
full aliases arr:  false

window := arr[1:3] has a capacity of 4, not 2, because the drawer runs from index 1 to the end of the array. So the first append had room, wrote 99 straight into arr[3], and arr changed under your feet even though you never mentioned arr. The second append needed five slots in a drawer that holds four, so it allocated a new array, copied everything across, and full stopped sharing memory with arr entirely. Nothing in the source code distinguishes those two calls. Only the capacity did.


Technical Depth: Three Words and One Branch

A slice value is a header, and unsafe.Sizeof of any slice is 24 bytes on a 64 bit platform regardless of the element type or the amount of data.

FieldMeaningRead it with
PointerAddress of element zero of the sectionNot directly accessible
LengthHow many elements you may indexlen(s)
CapacityHow many elements exist from the pointer to the end of the arraycap(s)

Indexing is checked against len, not cap: window[3] panics even though the capacity is 4. Re-slicing is checked against cap, which is why window[:4] is legal and gives you a view of data you could not otherwise reach.

nil Versus Empty

Both have length zero, and almost everything treats them identically. Almost.

Behaviorvar s []int (nil)s := []int{} (empty)
len and cap0 and 00 and 0
s == niltruefalse
append(s, 1)WorksWorks
for range sZero iterationsZero iterations
json.Marshalnull[]
reflect.DeepEqual(s, []int{})falsetrue

The rule that follows is short: prefer the nil slice. var out []int then append in a loop is idiomatic, needs no allocation until the first element, and reads better than out := []int{}. The one exception is a JSON API, where clients often break on null where they expected [], so an empty slice is worth the explicitness at that boundary. Never write a function that returns a nil slice for "none" and an empty slice for "some but zero", because no caller will notice the distinction and len(s) == 0 is the only check anyone writes.

Slicing, Including the Third Index

s[low:high] produces a slice of length high-low and capacity cap(s)-low. The bounds rule is 0 <= low <= high <= cap(s), and note that the upper limit is the capacity, not the length, which is what makes it possible to re-slice past the end of what you can currently see.

ExpressionLengthCapacityUsed for
s[2:5]3cap(s)-2A window
s[:0]0cap(s)Reusing a buffer
s[len(s):]0cap(s)-len(s)The unused tail
s[:cap(s)]cap(s)cap(s)Revealing the whole drawer
s[:0:0]00Handing out a slice nobody can append into
arr[:]len(arr)len(arr)Turning an array into a slice

The three-index form s[low:high:max] sets the capacity to max-low, and it is the one piece of slice syntax most Go programmers never learn. It is how you make aliasing impossible: return s[:n:n] and the caller's first append is guaranteed to allocate rather than to scribble on your array. When slicing an array or a pointer to an array the upper bound is len(arr), and slicing a string yields a string with no capacity at all.

How append Grows

append has exactly two behaviors, and the contract is worth stating precisely.

ConditionWhat append doesConsequence
len(s)+n <= cap(s)Writes in place and returns a header with a longer lengthOther slices over the same array see the writes
len(s)+n > cap(s)Allocates a bigger array, copies, writes, returns a new headerThe result no longer aliases the original

Because the second case returns a different pointer, you must always use the return value. append(s, x) on its own line is a bug in every case, and go vet catches exactly this one under the name of an unused result. The growth factor is deliberately not part of the language specification: current implementations roughly double small slices and grow large ones more gently, the threshold moved in Go 1.18, and the result is rounded up to a size class by the allocator. Do not write code, or tests, that depend on a particular capacity after growth.

What you should do instead is tell make the answer when you know it. make([]T, 0, n) for a result you are about to fill with n items turns a series of allocate-and-copy steps into one allocation, and it is the single highest-value micro-optimization in everyday Go.

copy, Delete and Insert

copy(dst, src) copies min(len(dst), len(src)) elements and returns that count. It never grows the destination, which is the mistake to watch for: copy(make([]int, 0, 10), src) copies nothing, because the destination's length is zero. It handles overlapping regions correctly, and it accepts a string as the source when the destination is []byte.

TaskModern formOlder idiom
Independent copyslices.Clone(s)append([]T(nil), s...)
Remove index i, keep orderslices.Delete(s, i, i+1)append(s[:i], s[i+1:]...)
Remove index i, order frees[i] = s[len(s)-1]; s = s[:len(s)-1]Same
Insert at islices.Insert(s, i, v)append(s[:i], append([]T{v}, s[i:]...)...)
Remove consecutive duplicatesslices.Compact(s)A hand-written loop

All of these return a new header, so all of them must be assigned back. slices.Delete also zeroes the elements it leaves behind at the tail, which matters when the elements contain pointers: without zeroing, the vacated slots keep objects alive that the program can no longer reach.

That last point generalizes into the one slice memory leak worth knowing. A slice keeps its entire backing array alive, not just the part it can see.

func firstLine(file []byte) []byte {
    i := bytes.IndexByte(file, '\n')
    if i < 0 {
        return file
    }
    return file[:i] // keeps the whole file in memory
}

Return bytes.Clone(file[:i]) instead and the rest of the file becomes collectable. Hold a ten-byte header out of a ten-megabyte read and you have retained ten megabytes; do it once per request and you have a leak that looks like a mysterious plateau in your heap graph.

The slices Package

Since Go 1.21 the standard library has generic helpers, and hand-written loops for these jobs are now the unusual choice.

FunctionDoes
slices.Sort, slices.SortFunc, slices.SortStableFuncSorts in place
slices.Contains, slices.Index, slices.IndexFuncLinear search
slices.BinarySearch, slices.BinarySearchFuncSearch a sorted slice, returns position and found
slices.Equal, slices.CompareElement-wise comparison, since == is illegal on slices
slices.Clone, slices.Grow, slices.ClipCopy, pre-reserve, and trim capacity to length
slices.Max, slices.Min, slices.ReverseWhat they say

slices.Clip is worth knowing next to slices.Clone, and the difference between them matters. Clip returns s[:len(s):len(s)]: it caps the capacity at the length so a later append is forced to allocate instead of writing into memory you did not mean to share. It does not release anything, because the pointer still points into the original array. Only Clone copies the data out and lets the original be collected.


Real World Example: The Parser That Returned the Same Row Three Times

This is a real production bug with a real production shape. Somebody notices that parsing allocates a slice per row, decides to reuse one buffer, and every stored row ends up being the last row. It survives code review because the reuse looks like a sensible optimization, and it survives unit tests because a single-row fixture cannot show it.

package main

import (
    "fmt"
    "slices"
    "strings"
)

var input = []string{
    "1001,alice,gb",
    "1002,bob,de",
    "1003,carol,fr",
}

// parseShared reuses one buffer and hands out slices of it. This is the bug.
func parseShared() [][]string {
    buf := make([]string, 0, 3)
    out := make([][]string, 0, len(input))
    for _, line := range input {
        buf = buf[:0]
        buf = append(buf, strings.Split(line, ",")...)
        out = append(out, buf)
    }
    return out
}

// parseCloned copies the fields out of the buffer before storing them.
func parseCloned() [][]string {
    buf := make([]string, 0, 3)
    out := make([][]string, 0, len(input))
    for _, line := range input {
        buf = buf[:0]
        buf = append(buf, strings.Split(line, ",")...)
        out = append(out, slices.Clone(buf))
    }
    return out
}
func main() {
    shared := parseShared()
    cloned := parseCloned()

    for i := range input {
        fmt.Printf("row %d shared=%v cloned=%v\n", i, shared[i], cloned[i])
    }

    fmt.Println("shared rows 0 and 2 equal:  ", slices.Equal(shared[0], shared[2]))
    fmt.Println("cloned rows 0 and 2 equal:  ", slices.Equal(cloned[0], cloned[2]))
    fmt.Println("shared rows share memory:   ", &shared[0][0] == &shared[2][0])
    fmt.Println("cloned rows share memory:   ", &cloned[0][0] == &cloned[2][0])
}

Output:

row 0 shared=[1003 carol fr] cloned=[1001 alice gb]
row 1 shared=[1003 carol fr] cloned=[1002 bob de]
row 2 shared=[1003 carol fr] cloned=[1003 carol fr]
shared rows 0 and 2 equal:   true
cloned rows 0 and 2 equal:   false
shared rows share memory:    true
cloned rows share memory:    false

Mechanically, nothing mysterious happened. buf = buf[:0] keeps the pointer and the capacity and sets the length to zero, which is precisely why it is the standard way to reuse a buffer. The three append calls then fit inside the capacity of 3 every time, so they write into the same backing array on every iteration, and out = append(out, buf) stores a copy of the header three times. Three identical pointers, three lengths of 3. By the time the loop ends, the array they all point at holds the last row, and that is what all three headers describe.

The reason this reaches production is the shape of the tests. One row passes. Two rows of identical data pass. Comparing lengths passes. Even a spot check of out[0] inside the loop passes, because at that moment the buffer really does hold row zero. You need at least two rows of different data, read after the loop has finished, to see it. The same bug wears other costumes: bufio.Scanner.Bytes() is documented as reusing its buffer, bytes.Buffer.Bytes() hands you the live internal slice, and any database driver that scans into a reused row buffer behaves the same way. In each case the rule is identical, and worth memorizing as a sentence: if you keep it after the next iteration, copy it.

slices.Clone is the fix, at a cost of one allocation per row, which is exactly the guarantee you are buying. But look harder at this particular function and the buffer should not exist at all. strings.Split already allocates a fresh slice on every call, so copying its result into a reused buffer and then cloning the buffer does two allocations where the honest version does one: out = append(out, strings.Split(line, ",")). Buffer reuse only pays when the producer writes into a buffer you supply, as Scanner and io.Reader do. Reusing a buffer to hold something that was freshly allocated anyway is a pessimization dressed as an optimization.

If you are writing the library rather than calling it, the third index is your defence. A function that returns buf[:n:n] gives the caller a slice whose capacity equals its length, so their first append must allocate and can never reach into the rest of your buffer. It does not stop them from writing to the elements they can see, so it is not a substitute for a clone when the data is genuinely shared, but it removes the entire class of "my append corrupted somebody else's data" surprise at the cost of one extra colon.


Common Mistakes

  1. Ignoring the return value of append. It may return a different pointer. Always write s = append(s, x).
  1. Believing "slices are passed by reference". The three-word header is copied. Writes to existing elements are visible to the caller; a reallocation inside the function is not.
  1. Storing a slice of a reused buffer. Every stored header points at the same array, so every stored row ends up being the last one. Clone it.
  1. Assuming s[a:b] has capacity b-a. It has cap(s)-a, so the window can append over data past its own end.
  1. Using copy into a zero-length destination. copy(make([]int, 0, 10), src) copies nothing. Make the destination the right length, not just the right capacity.
  1. Comparing slices with ==. It does not compile except against nil. Use slices.Equal.
  1. Returning a small sub-slice of a large buffer and keeping it. The whole backing array stays alive. Clone when the lifetime of the small piece outlives the big one.
  1. Testing an exact capacity after append. The growth factor is an implementation detail that has changed between releases.
  1. Distinguishing nil from empty in an API. Callers check len(s) == 0. The only place the difference is visible is JSON, where nil marshals to null.
  1. Deleting from a slice of pointers without zeroing the tail. The vacated slots keep objects alive. slices.Delete handles this for you.
  1. Building a matrix as [][]int and assuming rows are the same length. Nothing enforces that; either check it or use [R][C]int.

Best Practices

  • Start with var s []T and append; reach for make([]T, 0, n) the moment you know n, which is most of the time.
  • Assign the result of append, slices.Delete and slices.Insert back to the variable, every time.
  • Copy with slices.Clone before storing anything that came out of a reusable buffer, and say so in a comment.
  • Return s[:n:n] from library code so a caller's append cannot reach into your buffer.
  • Use the slices package instead of hand-written search, sort, compare and dedupe loops.
  • Reuse buffers with buf = buf[:0] only when a producer writes into a buffer you own, not to hold freshly allocated values.
  • Clone before holding a small window out of a large read, so the large read can be collected.
  • Prefer the nil slice as the empty value everywhere except a JSON response body, where [] is usually what the client expects.

Practice Exercises

  1. Find the Aliasing Line: Build a [6]int, slice window := arr[2:4], print len and cap, then append one element at a time and print arr after each. Identify the exact append at which arr stops changing, and state the capacity that caused it.
  1. Reproduce and Fix the Parser Bug: Write parseShared from scratch with four rows of different data and confirm all four results are identical. Fix it three ways: slices.Clone, allocating inside the loop, and returning buf[:n:n]. Say which fix is appropriate for which situation.
  1. The Empty Destination: Write copy(make([]int, 0, 10), []int{1,2,3}) and print the returned count. Then fix it so all three elements land, and explain in one sentence which of length and capacity copy actually consults.
  1. Delete Four Ways: Remove the middle element of a ten-element slice using slices.Delete, the append idiom, and the swap-with-last trick. For each, report whether order is preserved, how many elements moved, and what happens to the final slot. Then repeat with a slice of pointers and explain why zeroing the tail matters.