Home >Backend Development >Golang >Why Does Setting One Go Variable Overwrite the Other?

Why Does Setting One Go Variable Overwrite the Other?

DDD
DDDOriginal
2024-10-24 08:09:30955browse

Why Does Setting One Go Variable Overwrite the Other?

Go variables being overwritten

In this code, the author encounters an issue where the variable pathA is overwritten when setting pathB. This suggests that both variables are referencing the same underlying array, resulting in modifications to one affecting the other.

The issue stems from the use of the append() function with slices in Go. When appending an element to a slice, Go checks if the underlying array has sufficient capacity to accommodate the new element. If not, it allocates a larger array and copies the existing elements.

In the code provided, the slice route is used to create both pathA and pathB. If the capacity of the underlying array of route is exceeded when appending to either pathA or pathB, a new array is allocated. However, since both pathA and pathB are derived from the same slice, they share the same underlying array.

To avoid this issue, it's necessary to create an independent copy of route before using it to initialize pathA and pathB. This can be achieved using the make() and copy() functions, as shown in the author's second edit:

<code class="go">newRoute := make([]int, len(prePaths[i]), (cap(prePaths[i])+1)*2)
copy(newRoute, prePaths[i])

pathA := append(newRoute, nextA)
pathB := append(prePaths[i], nextB)</code>

In this revised code, newRoute is a separate slice with its own underlying array. This ensures that pathA and pathB have independent copies of the data, preventing modifications to one from affecting the other.

The above is the detailed content of Why Does Setting One Go Variable Overwrite the Other?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn