Understanding the Behavior of append() on Slices
Despite the initial assumptions of slice as a pointer, the provided code demonstrates that the append() operation does not directly affect the original slice. This is because, in Go, everything is passed by value, including slices. So when you pass a slice to a function or assign it to a new variable, you are only passing a copy of the slice header.
The slice header contains information such as the length of the slice, its capacity, and a pointer to the underlying array. When the append() operation is performed on a slice, a new array is allocated if necessary to accommodate the new elements. The slice header is then updated to point to the new array, and the new elements are copied over. This new slice header is returned as the result of the append() call.
In the example code, you assign the return value of the append() operation to the slice1 variable. This means that slice1 now points to a different array than slice. Any changes made to the elements of slice1 will not be reflected in slice, and vice versa.
To achieve the behavior where both slice and slice1 refer to the same array, you would need to use a pointer to a slice instead of a slice itself. For example:
func main() { slice := make([]int, 10, 10) slice[0] = 0 slice[1] = 1 slicePtr := &slice slice1 := *slicePtr slice1[0] = 10000 fmt.Println(slice) *slicePtr = append(*slicePtr, 100) (*slicePtr)[0] = 20000 fmt.Println(slice) }
In this example, both slice and slice1 point to the same underlying array, so any changes made to one will be visible in the other.
以上是Append() 如何影響 Go 中的切片?的詳細內容。更多資訊請關注PHP中文網其他相關文章!