Home  >  Article  >  Backend Development  >  Are Go Variables Being Overwritten Due to Slice Misunderstanding?

Are Go Variables Being Overwritten Due to Slice Misunderstanding?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 08:09:02736browse

Are Go Variables Being Overwritten Due to Slice Misunderstanding?

Go Variables Being Overwritten (Bug?)

In this instance, the issue lies in understanding how slices function in Go. A slice consists of a pointer to an array, along with its length and capacity. When appending an element to a slice, it first checks if extending the slice would exceed the capacity of its underlying array. If so, a larger array is allocated, existing elements are copied to it, and the capacity is updated. Then, the new element is added to the end of the array, and the length is updated.

In your code, you have the following lines:

<code class="go">pathA := append(route, nextA)
pathB := append(route, nextB)</code>

There are two possibilities here:

  1. If len(route) equals cap(route), a new backing array will be allocated, and pathA and pathB will have distinct values.
  2. If len(route) is less than cap(route), pathA and pathB will end up sharing the same backing array. The last element in the array will be nextB, since it was executed second.

It appears that the first case is true for the initial loop iterations, after which the second case occurs. This issue can be resolved by manually making a copy for one of these paths using copy() and make().

The above is the detailed content of Are Go Variables Being Overwritten Due to Slice Misunderstanding?. 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
Previous article:express-goNext article:express-go