Cause of Variable Overwriting in Go
Your code encounters a variable overwriting issue because you are creating new slices (pathA and pathB) by appending elements to the same backing array (route) within a loop.
Background on Slices in Go:
- A Go slice is a data structure that represents a contiguous block of elements of the same type.
- Slices have a length (the number of elements currently stored) and a capacity (the maximum number of elements it can hold).
- When you modify a slice, it may trigger the allocation of a new backing array if the capacity is exceeded.
Problem with Your Code:
In your code, you are creating two new slices, pathA and pathB, using the append function:
pathA := append(route, nextA)
pathB := append(route, nextB)
Copy after login
Here's what happens:
- Initially, route has a capacity that can fit both nextA and nextB. So, two new slices (pathA and pathB) are created with the same backing array as route.
- As the loop progresses and you continue appending to route, its capacity eventually exceeds its length.
- In the subsequent iteration of the loop, a new backing array is allocated for route. However, pathA and pathB still refer to the old backing array.
- When you append nextB to route, it writes to the last element of the old backing array, which is shared by both pathA and pathB.
- As a result, both pathA and pathB end up with the same final value.
Solution:
To avoid this overwriting, you need to ensure that pathA and pathB have unique backing arrays. You can achieve this by manually creating a new slice for one of them using make and copy:
newRoute := make([]int, len(route), (cap(route)+1)*2)
copy(newRoute, route)
if i % 2 == 0 {
pathA := append(newRoute, nextA)
} else {
pathB := append(newRoute, nextB)
}
Copy after login
The above is the detailed content of Why Does Variable Overwrite Occur in Go When Appending to Slices from the Same Array?. For more information, please follow other related articles on the PHP Chinese website!