A Go Slice Is a View on an Array, So append May Share or Copy Its Elements
An array in Go has a fixed size that is part of its type ([4]int). A slice ([]int) is a small header (a pointer to an underlying array, a length and a capacity) describing a window on that array. Slicing a slice creates another window on the same array, so writes through one are visible through the other. append writes into the shared array while there is capacity left, and allocates a new array when there isn't, so whether two slices share data can change silently.
Working with Slices
var langs []string // nil slice, length 0
langs = append(langs, "Go") // always reassign the result of append
langs = append(langs, "JavaScript")
numbers := []int{4, 56, 76, 20, 43, 11}
middle := numbers[2:6] // [76 20 43 11]: shares numbers' array
middle[0] = 0 // numbers is now [4 56 0 20 43 11]
len(s) is the number of visible elements; cap(s) is how far the window could grow before append needs a new array.
The Aliasing Trap
a := make([]int, 3, 10) // len 3, cap 10
b := append(a, 1) // fits: writes into a's array
c := append(a, 2) // also fits: overwrites the same slot
fmt.Println(b[3], c[3]) // 2 2
Strings Are Read-Only Byte Slices
A Go string is an immutable sequence of bytes, usually UTF-8. Indexing returns a byte, not a character: "é" is two bytes. Iterate with for _, r := range s to get runes (Unicode code points), and convert with []byte(s) or []rune(s) when you need to modify a copy.
References
- Programming Languages MOC - hub for language notes.
- Go Has a Single Loop Keyword, for -
rangeover slices and strings. - Go blog: Go Slices, usage and internals - headers, capacity and append.
- A Tour of Go: Slices - slices as views on arrays.
Review cards
Flashcard How do you make the result of `append` independent of the original slice?
Copy first, then append to the copy: append([]int(nil), a...), or make plus copy.
Quiz With `a := make([]int, 3, 10)`, what does `append(a, 1)` return?
- A slice of length 4 that shares
a's underlying array - A slice backed by a new array, since
appendalways copies - Nothing: it changes
ain place to length 4 - A slice backed by a new array, since
aisn't empty
Capacity 10 leaves room, so nothing is allocated and the result shares a's array; a keeps length 3. Only when capacity runs out does append allocate a new array and copy.