Home >Backend Development >Golang >Why Are Go Variables Overwritten When Multiple Slices Are Appended?
Go Variables Being Overwritten (Bug?)
This issue occurs when setting multiple variables, each defined by appending an element to an existing slice, but one variable is overwritten when the second is set.
Consider the following code snippet:
<code class="go">for i := 0; i < len(prePaths); i++ { route := prePaths[i] nextA := nextLine[i] nextB := nextLine[i+1] pathA := append(route, nextA) pathB := append(route, nextB) postPaths = append(postPaths, pathA) postPaths = append(postPaths, pathB) }</code>
The problem lies in the second line of the loop, where both 'pathA' and 'pathB' are defined as slices appended with an element. However, appending to a slice does not create a new slice; instead, it modifies the existing slice.
In this scenario, 'route' is the existing slice being appended to. Thus, when 'pathA' is created, it shares the same underlying array as 'route'. Subsequently, when 'pathB' is created, it also shares the same array as 'pathA'.
Since 'pathB' is the last slice appended to, the last element in the underlying array is set to the value appended to 'pathB'. As a result, 'pathA', which shares the same array, also reflects this change. This explains why 'pathA' gets overwritten when 'pathB' is set.
To resolve this issue, one must create independent slices for 'pathA' and 'pathB'. This can be achieved by using the 'make' and 'copy' functions.
Here's a modified code snippet that creates independent slices:
<code class="go">for i := 0; i < len(prePaths); i++ { newRoute := make([]int, len(prePaths[i]), (cap(prePaths[i])+1)*2) copy(newRoute, prePaths[i]) nextA := nextLine[i] nextB := nextLine[i+1] pathA := append(newRoute, nextA) pathB := append(prePaths[i], nextB) postPaths = append(postPaths, pathA) postPaths = append(postPaths, pathB) }</code>
In this code, 'newRoute' is a new slice created using the 'make' function, ensuring that it has independent data. The 'copy' function is then used to copy data from 'prePaths[i]' into the new slice 'newRoute'. Afterward, 'pathA' and 'pathB' are defined using independent slices, resolving the initial issue.
The above is the detailed content of Why Are Go Variables Overwritten When Multiple Slices Are Appended?. For more information, please follow other related articles on the PHP Chinese website!