The Append Gotcha

When Append Modifies the Original Slice

Prevent `append` from modifying the original slice by cloning it first to ensure a separate underlying array.

The append function modifies the original slice's underlying array if there is sufficient capacity, causing changes to be visible in other slices sharing that array. To prevent this, create a new slice with a fresh underlying array using slices.Clone before appending, or manually copy the data into a new slice.

import "slices"

// Original slice
original := []int{1, 2, 3}

// Safe: Clone first to break the shared array link
copy := slices.Clone(original)

// Now append to the copy without affecting original
result := append(copy, 4)

// original remains [1, 2, 3]
// result is [1, 2, 3, 4]