In Go, it's common practice to encounter code like this:
<code class="go">func main() { slice := make([]int, 10, 10) slice[0] = 0 slice[1] = 1 slice1 := slice slice1[0] = 10000 fmt.Println(slice) slice1 = append(slice1, 100) slice1[0] = 20000 fmt.Println(slice) }</code>
Upon running this code, you'd notice something peculiar:
[10000 1 0 0 0 0 0 0 0 0] [10000 1 0 0 0 0 0 0 0 0]
Intuitively, one might assume that slice and slice1 are references to the same underlying array. However, this observation raises the question: why does slice remain unchanged after the append operation on slice1?
Understanding the Nature of Slices
To unravel this mystery, it's essential to understand the fundamental nature of slices in Go. Slices are not pointers; they are encapsulations of an array. Specifically, a slice comprises three elements:
When assigning slice1 to slice, you're creating a new slice header that points to the same underlying array as slice. As a result, any modifications made to slice1 are directly reflected in slice.
The Impact of append()
Now, let's analyze the impact of append() on slice1. The append() function takes a slice as an argument and returns a new slice. This new slice may or may not refer to the same underlying array as the original slice.
In this case, since the slice initially has capacity equal to its length, any append() operation with more than 0 elements necessitates creating a new, larger array. This is precisely what slice1 = append(slice1, 100) does. It allocates a new array, copies over the contents of the old one, and returns a new slice header.
The assignment of the resulting slice header to slice1 replaces the previous slice header in slice1. This means that slice1 now points to a different underlying array than slice does. Consequently, any subsequent modifications made to slice1 do not affect slice, and vice versa.
Conclusion
While slices may be commonly mistaken for pointers, they are actually distinct value types. This intrinsic difference manifests itself during append() operations. Assignments such as slice1 = append(slice1, 100) create a new slice header that may or may not point to the same underlying array as the original slice. This is critical to keep in mind when manipulating slices in Go code.
The above is the detailed content of What\'s the Mystery Behind Slice Behavior in append() Operations in Go?. For more information, please follow other related articles on the PHP Chinese website!