"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Does Variable Overwrite Occur in Go When Appending to Slices from the Same Array?

Why Does Variable Overwrite Occur in Go When Appending to Slices from the Same Array?

Published on 2024-11-10
Browse:421

Why Does Variable Overwrite Occur in Go When Appending to Slices from the Same Array?

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)

Here's what happens:

  1. 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.
  2. As the loop progresses and you continue appending to route, its capacity eventually exceeds its length.
  3. 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.
  4. 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.
  5. 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)
}
Release Statement This article is reprinted at: 1729727920 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3