Home > Article > Backend Development > Why Does Slice Append Behavior Change When Creating New Slices from a Loop?
Unexpected Slice Append Behavior
Issue Introduction
When appending elements to a slice within a loop, subsequent attempts to create new slices from the looped result exhibit unexpected behavior. Specifically, the last append element overwrites the results of previous appends. This issue arises when creating new slices based on a slice obtained from a loop iteration.
Analysis
The observed behavior stems from the fact that both Go slices and arrays use the same underlying data structure. When appending to a slice, Go creates a new slice object that references the same underlying array. This means that any changes made to the original slice will also affect the new slices.
Solution
To avoid this behavior, it is essential to copy the slice before making any modifications. This creates a new slice object that has its own independent reference to the underlying array. The idiomatic way to achieve this is to use the copy function:
<code class="go">func makeFromSlice(sl []int) []int { result := make([]int, len(sl)) copy(result, sl) return result }</code>
By assigning the result of makeFromSlice(i) to j in the main function, we create a new slice that is independent of the original i slice. This new slice can be safely modified without affecting the original.
Contrast with Slice Literals
Slice literals, such as {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, always allocate a new underlying array when appended beyond their capacity. This explains why sliceFromLiteral behaves as expected.
Conclusion
When working with slices, always remember to make a copy before modifying them. This ensures that changes made to new slices do not affect the original. The copy function provides an idiomatic and efficient way to do this.
The above is the detailed content of Why Does Slice Append Behavior Change When Creating New Slices from a Loop?. For more information, please follow other related articles on the PHP Chinese website!