Suppose you read a large file or API response into buf, slice out the 16 bytes you need with part := buf[:16], and store part in a cache. You think you're keeping a tiny snippet, yet your service's RAM quietly balloons.
The trap is how Go slices work under the hood. A slice is just a header (ptr, len, and cap) pointing to a shared backing array in memory. Writing buf[:16] copies nothing: part points to that same array, and changing part[0] mutates buf[0]. As long as part stays alive, the garbage collector (GC) cannot free the original buffer, even long after buf goes out of scope. The Go blog illustrates this with FindDigits: a function reads an entire file, regex-slices a few digits, and accidentally pins the whole file in RAM.
To break the link to the old buffer, copy the bytes into a fresh slice:
// Risky: part keeps the entire buf backing array in memory
part := buf[:16]
// Safe: allocate a separate 16-byte array
saved := make([]byte, len(part))
copy(saved, part)
// In Go 1.21+, the same thing in one line:
// saved := slices.Clone(buf[:16])
After copy or slices.Clone, saved lives in its own tiny array, and the old buffer is freed as soon as no other references remain. You only need to copy when a short slice outlives a large buffer—otherwise, it's just an unnecessary allocation.
