Slice backing array
A slice header points at an array that actually holds the elements. Several slices can share one array. append may allocate a new array and leave old slices on the old one.
Detailed Explanation
s := make([]int, 3, 8) allocates an 8-integer array and a header with len=3. t := s[1:3] is another header into the same array. t[0] = 9 writes s[1]. The array is the object the GC sees; the headers are three-word values.
append and identity. If append fits in cap, it writes the array in place. Every header that still points at that array sees the write if it overlaps. If append does not fit, a new array is allocated, the elements are copied, and only the returned header points at the new array. Old headers still see the old array.
Full slice expressions. s[i:j:k] sets cap to k-i so a later append on that header cannot write past k. Use this when you pass a window to a callee you do not trust to leave the tail alone.
Conversion from array. a[:] is a header to a. If a is a local array that does not escape, the slice must not outlive the function — or the array escapes. Returning a[:] from a function that has var a [32]byte puts the array on the heap.
What it costs. Understanding the backing array is how you avoid accidental sharing and accidental leaks. Copy when you need independence. Clip capacity when you need to forbid append-into-tail. Leave sharing in place when you want zero-copy windows over a buffer you own.
Code Examples
package main
import "fmt"
func main() {
s := make([]int, 2, 4)
s[0], s[1] = 1, 2
t := s[0:2]
s = append(s, 3) // same array if cap allows
t[0] = 9
fmt.Println(s, t)
}func window(s []byte) []byte {
return s[1:3:3] // cap clipped
}Common Gotchas
After a growing `append`, old headers do not see new elements
they still point at the previous array.
Aliased headers plus in-place `append` overwrite "other" slices
Aliased headers plus in-place `append` overwrite "other" slices
`cap` is measured from the header's start, not from array index 0
`cap` is measured from the header's start, not from array index 0
`copy` is how you get a new array of `len` elements
`copy` is how you get a new array of `len` elements