Understanding Slice Modification in Go
In Go, slice variables behave differently from typical arrays. This can lead to unexpected behavior, especially when modifying slices.
The Mystery of the Changing Original Slice
Consider the following code:
import "fmt" func main() { A := []int{3, 4, 5, 3, 7} fmt.Println("Initial slice: ", A) funcSome(A) fmt.Println("Modified slice: ", A) } func funcSome(slice []int) { fmt.Println("Inside function, original slice: ", slice) temp := slice // copy by value temp[0] = 10 fmt.Println("Inside function, modified temp: ", temp) fmt.Println("Inside function, original slice: ", slice) }
When you run this code, you might be surprised to find that modifying the temporary slice, temp, also modifies the original slice, A.
Delving into Slice Internals
To understand this behavior, we need to dive into the internal structure of slices. A slice variable consists of three components:
When you assign a slice to a new variable by value, as we do with temp := slice, you are creating a shallow copy. This means that the new slice (temp) shares the same backing array and pointer as the original slice (slice).
The append() Dilemma
The append() function in Go adds elements to a slice by creating a new backing array and copying the existing data into it. However, if the new slice has insufficient capacity, the append() function will automatically increase the capacity by reallocating a larger backing array.
In your example, the remove() function uses append() to create a new slice. Since temp and A share the same backing array, any modification to the new slice will also affect the original slice.
Conclusion
Understanding slice modification in Go requires familiarity with its unique internal structure. Remember that when copying slices by value, you are creating a shallow copy, which shares the same backing array. This behavior can lead to unexpected consequences when modifying slices.
The above is the detailed content of Why Does Modifying a Go Slice Copy Also Change the Original?. For more information, please follow other related articles on the PHP Chinese website!