Go Reference ยท Concepts
Go slice aliasing and append
Reference for Go slice aliasing: how slices share a backing array, when append writes in place or reallocates, full slice expressions, copy and slices.Clone.
A slice is a small descriptor: a pointer to an element of an underlying array, a length and a capacity. Assigning a slice, passing it to a function or cutting it with s[i:j] copies only the descriptor. The new slice and the old one then alias the same array, so a write through one is visible through the other.
append is where this gets subtle. If the slice has spare capacity, append writes into the existing array and returns a slice over it; any other slice that covers those elements sees the change. If the capacity is used up, append allocates a bigger array, copies, and the new slice no longer shares memory with the old one. Whether two slices are still linked can therefore depend on how many elements they hold.
a := []int{1, 2, 3, 4} b := a[1:3] // shares memory with a b[0] = 99 // a is now [1 99 3 4]
Try it
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.
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.
Syntax
s[low:high] // length high-low, capacity cap(s)-low s[low:high:max] // length high-low, capacity max-low (full slice expression) append(s, elems...) // may or may not allocate copy(dst, src) int // copies min(len(dst), len(src)) elements slices.Clone(s) // independent copy (Go 1.21)
| Operation | Shares the array with the original? |
|---|---|
t := s |
Yes, always. |
t := s[i:j] |
Yes. t can even reach elements past j with t[:cap(t)]. |
t := s[i:j:k] |
Yes, but append beyond k-i elements copies. |
t := append(s, x) |
Yes if len(s) < cap(s), otherwise no. |
t := slices.Clone(s) |
No. |
copy(t, s) |
No: copies elements into t's own array. |
Rules for append: the result must be assigned (usually to the same variable), because the returned slice header may differ from the argument. When capacity is exceeded the runtime allocates a larger array. The growth formula is an implementation detail: roughly doubling for small slices and growing more slowly for large ones, and rounded up to memory size classes. Never write code that depends on exact capacities.
Errors and edge cases: s[i:j] on a slice panics unless 0 <= i <= j <= cap(s); note that j may be larger than len(s). Strings and arrays are stricter: j must not exceed their length. A nil slice appends fine. copy never grows its destination, so copy into an empty slice copies nothing. Appending a slice to itself (append(s, s...)) is safe.
Usage notes
- Small slice, big array. Keeping
s[:2]of a million-element slice keeps the whole array alive. Copy the part you need (slices.Clone(s[:2])) to let the rest be freed. - Remove elements with
slices.Delete. It shifts the tail and, since Go 1.22, zeroes the vacated slots so pointers there can be collected. Old idioms withappend(s[:i], s[i+1:]...)modify the original array. - Filter in place with
s[:0]as the destination:out := s[:0]; for ... { out = append(out, v) }. The original slice's contents are overwritten, which is the point and the danger. - Returning sub-slices from a method hands out a window into your internal array. Return a copy, or document that callers must not modify or append.
- Function parameters. Passing a slice shares the elements, so a callee can change them, but an
appendinside the callee is invisible to the caller unless the slice is returned. - Concurrent use. Two goroutines appending to slices that share capacity race on the same memory. Give each goroutine its own slice, or use
s[:len(s):len(s)]to force a copy. - Pre-size when you can.
make([]T, 0, n)avoids repeated growth. - Maps of slices.
m[k] = append(m[k], v)works because a missing key gives a nil slice.
Related
- slice, append(), copy(), make(), Zero values
- Lessons: Slices, Slice Internals, The slices and maps Packages