Understand the contract
append returns a slice containing the original elements followed by the new ones. Always keep that returned value. If capacity is sufficient, append reuses existing storage; otherwise it allocates another array. Code that depends on unrelated slices staying independent should not rely on whichever allocation happens today.
Appending to a subslice can overwrite an element visible through another slice when they share capacity. To create a separate sequence, allocate a destination and use copy, or append into a nil destination. Both approaches copy element values, so pointed-to objects can still be shared.
Work through the example
The example deliberately gives base spare capacity. Appending nine to prefix writes into the second position of base, producing [1 9]. The independent slice receives its own element storage before appending three. Printing base again shows why the two operations have different effects.
package main
import "fmt"
func main() {
base := make([]int, 2, 4)
base[0], base[1] = 1, 2
prefix := base[:1]
prefix = append(prefix, 9)
independent := append([]int(nil), base...)
independent = append(independent, 3)
fmt.Println(base, prefix, independent)
}Watch this boundary
Capacity growth is an implementation detail, not a promise that capacity doubles at every append. Preallocate when you know an approximate element count, but measure before adding complicated allocation strategies. A full slice expression such as base[:1:1] can restrict capacity; it does not copy existing elements.
Practice with a changed input
Replace base[:1] with base[:1:1] and predict whether the append can overwrite base[1]. Then repeat the exercise with a slice of pointers and inspect what remains shared.
Lesson 14 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services