Problem Description:
Consider the following Go code:
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) }
The initial output is as expected: both slice and slice1 show the same values. However, after the append operation on slice1, the values of slice remain unchanged. This behavior seems counterintuitive, given the assumption that slices are pointers.
Explanation:
The append function does not modify slice1. Go passes all values by value, so slice1 receives a copy of slice. The append operation creates a new array, since the original array has reached its capacity. It then copies the contents of the old array into the new one and returns a new slice header pointing to the new array.
The assignment of the return value to slice1 changes slice1. However, slice remains unaffected because it is a separate variable pointing to the original array. Therefore, any changes made to the elements of slice1 or slice after the append operation will not be reflected in the other.
In summary, slices in Go are pass-by-value, and append creates new slices with new underlying arrays when necessary. This means that changes made to one slice are not reflected in other slices pointing to the original array.
The above is the detailed content of Why Doesn't Appending to a Go Slice Affect Other Slices Pointing to the Same Underlying Array?. For more information, please follow other related articles on the PHP Chinese website!