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

Mary-Kate Olsen
Release: 2024-10-24 08:11:01
Original
396 people have browsed it

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)
Copy after login

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)
}
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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!