Home  >  Article  >  Backend Development  >  Why are Go Variables Being Overwritten?

Why are Go Variables Being Overwritten?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-24 07:54:30791browse

Why are Go Variables Being Overwritten?

Go Variables Being Overwritten

In a Go routine, a user reported an issue where one variable was being overwritten when another was set. Specifically, the user created two integer lists named pathA and pathB. When pathA was extended with a new value from a triangle, it was initially set correctly but was later overwritten by pathB.

Investigations

The issue arises due to the sharing of backing arrays between slices. In Go, when a slice is extended beyond its capacity, a new backing array is allocated, and the existing elements are copied to the new array. However, if the slice's length is less than its capacity, the slice and its appended elements will share the same backing array.

In the user's code, as the size of pathA and pathB grew, it reached a point where the slice's length exceeded its capacity and a new backing array was allocated for pathA. However, since pathB was created next, it ended up using the same backing array.

Solution

To solve this issue, the user needed to ensure that both pathA and pathB had independent backing arrays. This was achieved by manually allocating a new slice for pathB using make() and copying the old data using copy().

Revised Code

Here is the modified code:

<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>

This code ensures that both pathA and pathB have their own backing arrays, preventing the overwriting issue.

The above is the detailed content of Why are Go Variables Being Overwritten?. 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