Trace backing array aliasing
Trace backing array aliasing
Two slices may describe overlapping regions of the same array. Assignment copies a slice descriptor, not its elements. Updating a shared element through one slice is visible through the other. This sharing is called aliasing.
package main
import "fmt"
func main() { a := []int{10, 20, 30} b := a[1:] b[0] = 99 fmt.Println(a, b) c := a c[0] = 7 fmt.Println(a, c)}b[0] and a[1] refer to the same element. c[0] also updates a[0]. A function changing a slice element can affect its caller even though arguments are passed by value.
Expected output:
[10 99 30] [99 30][7 99 30] [7 99 30]Observe reuse and separation after append
package main
import "fmt"
func main() { a := make([]int, 2, 3) a[0], a[1] = 1, 2 b := append(a, 3) b[0] = 8 fmt.Println(a, b) c := append(b, 4) c[0] = 9 fmt.Println(a, b, c)}b shares storage because the first append fits. c needs a new array because b has length and capacity 3 before appending. The copied integer elements no longer share storage. Nested pointers or slices may still refer to shared data.
Expected output:
[8 2] [8 2 3][8 2] [8 2 3] [9 2 3 4]Try it locally
Create []int{4,5,6} and a view of its last two elements. Change the first element of the view to 50. Print both.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 06: Trace backing array aliasing
Check the lesson objective before moving on.
What does assigning b = a copy for slices?
After append allocates a new integer array, does changing an integer in the result change the original array?