GO / CHAPTER 03
Slices and shared backing arrays
IntermediatePredict aliasing and make independent copies when needed.
By the end of this chapter
- Distinguish slice length and capacity
- Recognize shared element storage
- Use copy with an allocated destination
The idea
Enter with arrays and indexes understood. A slice describes a window into an underlying array. Its length determines which indexes are valid; its capacity describes how far it can grow within that backing storage. Assigning a slice copies the descriptor rather than copying all elements. Two slices can therefore observe changes to shared elements even though the slice variables themselves are separate.
append returns a new slice value and may reuse the backing array or allocate another one. Save that returned value, and avoid relying on allocation happening unless the capacity contract requires it. For an independent element copy, allocate a destination of the required length and call copy. Copying a slice of pointers still copies pointer values, not the pointed-to objects; decide what independence the application actually needs.
package main
import "fmt"
func main(){
a:=[]int{3,5,7}
b:=a[1:]
b[0]=9
fmt.Println(a)
}[3 9 7]
b starts at a’s second element and shares its storage. Writing b[0] therefore changes a[1].
Try it yourself
Create an independent copy of a []int and demonstrate that changing the copy leaves the original unchanged.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING