Skip to Content
Skip to content
Why Go append Mutates Another Slice (and How to Stop It)
Beginner
Tutorials

Why Go append Mutates Another Slice (and How to Stop It)

See why two Go slices overwrite each other after append and prevent it with full-slice expressions or slices.Clone. After this, shared slice headers will not corrupt sibling values.

Updated 5 min read GoData Structures and Algorithms

Skip ahead: If you already know why len and cap diverge, skip to "Case 2: prove backing-array sharing with memory addresses" or the comparison table below.

You append one item to a new slice variable, and a completely different slice changes underneath you. Nothing is broken in Go—both slices shared the same backing array because append still had spare capacity. Once you understand the 3-word slice header, every aliasing bug, function-argument surprise, and nil-vs-empty JSON difference makes complete sense. Verified on golang:trixie (Go 1.27.4).

Case 1: two branches append to the same base slice

Here base has length 2 and capacity 4. Both admin and guest are built by appending to base, and guest quietly overwrites admin[2]:

package main

import (
	"fmt"
	"slices"
)

func main() {
	base := make([]string, 2, 4)
	base[0], base[1] = "read", "list"

	admin := append(base, "delete")
	guest := append(base, "help")
	fmt.Println("aliased admin:", admin)
	fmt.Println("aliased guest:", guest)

	safeAdmin := append(base[:2:2], "delete")
	safeGuest := append(slices.Clone(base), "help")
	fmt.Println("safeAdmin:", safeAdmin)
	fmt.Println("safeGuest:", safeGuest)
	fmt.Println("base:", base)
}
aliased admin: [read list help]
aliased guest: [read list help]
safeAdmin: [read list delete]
safeGuest: [read list help]
base: [read list]

Because base had capacity 4, append(base, "delete") wrote "delete" into slot [2] of base's backing array. The next line, append(base, "help"), saw the exact same spare slot [2] and overwrote "delete" with "help". Meanwhile base itself still prints [read list] because its own len stayed 2—even though its hidden slot [2] changed twice.

Diagram showing a Go slice header with pointer, length, and capacity pointing to a shared backing array
Two slices sharing the same backing array when spare capacity remains.

Case 2: prove backing-array sharing with memory addresses

A Go slice is a small 3-field header: {pointer, len, cap}. Printing &s[0] shows the exact address of element 0 so you can see when append reuses the array vs. allocates a new one—and what happens when you pass a slice into a helper function:

package main

import "fmt"

func replaceFirst(s []string) {
	s[0] = "changed"
	s = append(s, "extra")
	fmt.Println("inside func:", s)
}

func main() {
	s := make([]string, 2, 4)
	s[0], s[1] = "a", "b"
	t := append(s, "c")
	fmt.Printf("same array? &s[0]=%p &t[0]=%p\n", &s[0], &t[0])

	u := s[:2:2]
	v := append(u, "d")
	fmt.Printf("after s[:2:2]: &u[0]=%p &v[0]=%p\n", &u[0], &v[0])

	replaceFirst(s)
	fmt.Println("caller s:", s)
}
same array? &s[0]=0x1cb68dcfc080 &t[0]=0x1cb68dcfc080
after s[:2:2]: &u[0]=0x1cb68dcfc080 &v[0]=0x1cb68dcfc0c0
inside func: [changed b extra]
caller s: [changed b]

Two key rules jump straight out of those addresses:

  • Capping capacity forces a fresh allocation on append: before s[:2:2], &s[0] and &t[0] were identical (...080). After capping cap to 2 with the full-slice expression s[:2:2], append(u, "d") had no room left and allocated a brand-new array (...0c0).
  • Functions copy the slice header, not the backing array: replaceFirst(s) changed s[0] in the caller because both headers pointed at the same array, but its local s = append(s, "extra") only updated the function's copy of len. The caller's s remained length 2.

Case 3: nil slice vs. empty slice in encoding/json

In Go, var s []string (a nil slice) and []string{} (an empty non-nil slice) behave identically for len, range, and append—until you encode them to JSON:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	var nilSlice []string
	emptySlice := []string{}

	b1, _ := json.Marshal(nilSlice)
	b2, _ := json.Marshal(emptySlice)
	fmt.Printf("nilSlice:   len=%d json=%s\n", len(nilSlice), b1)
	fmt.Printf("emptySlice: len=%d json=%s\n", len(emptySlice), b2)
}
nilSlice:   len=0 json=null
emptySlice: len=0 json=[]

If a frontend JavaScript client expects an array (items.map(...)) instead of null, initialize empty API response slices with make([]T, 0) or []T{} rather than leaving them nil.

Which isolation pattern to pick

FixHow it worksWhen to use
base[:n:n] (full-slice expression)Caps the view at cap = n, so append allocates a new arrayWhen you only want to protect against future append calls
slices.Clone(base)Copies elements into a brand-new backing array immediatelyWhen index writes (s[0] = ...) also need full isolation
copy(dst, src)Copies into an existing pre-allocated sliceWhen reusing a caller-provided buffer in hot paths
Return the slice from helpersfunc add(s []T) []TWhenever a helper function calls append

Common mistakes

  • Assuming sub := items[:2] makes an independent copy: slicing never allocates—it returns a window over the exact same array, with cap still extending to the end of items.
  • Appending inside a helper without returning the slice: the caller never sees the new len or a reallocated array.
  • Keeping a small slice of a huge buffer: header := bigFile[:64] keeps the entire multi-megabyte bigFile array pinned in memory until header is garbage-collected. Copy those 64 bytes with slices.Clone(bigFile[:64]) so the large array can be freed.

⚠ Warning: Sharing a slice across goroutines and appending in one while reading in another is a data race even if you think the indices do not overlap. Clone the slice before handing it to another goroutine.

What happens if you skip this

Two permission lists, route slices, or batch buffers share a base slice with spare capacity. Every unit test passes when run alone, then production requests overwrite each other's last item—or a 64-byte slice keeps a 50 MB upload pinned in RAM until the container OOMs.

Related course: Go for Beginners.

About

See why two Go slices overwrite each other after append and prevent it with full-slice expressions or slices.Clone. After this, shared slice headers will not corrupt sibling values.

Responsible
Jay P
Last Update
11/27/2026
Reading Time
5 min
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.