Home > Backend Development > Golang > Strange behavior of append in Go

Strange behavior of append in Go

王林
Release: 2024-02-02 14:13:26
forward
1047 people have browsed it

Go 中追加的奇怪行为

Question content

I am trying to solve the subsetting problem on LeetCode using Go. I came up with the following solution:

func subsets(nums []int) [][]int {
    sol := make([][]int,0)
    temp:= make([]int,0)

    var backtrack func(idx int)
    backtrack = func(idx int) {
        sol = append(sol, temp)
        fmt.Println(temp, append([]int{},temp...))

        if idx == len(nums) {
            return
        }

        for i:= idx; i<len(nums);i++{
            temp = append(temp,nums[i])
            backtrack(i+1)
            temp = temp[:len(temp)-1]
        }

    }
    backtrack(0)
    return sol

}
Copy after login

However, this solution is incorrect. I noticed that I need to use append(sol,append([]int{},temp...)) instead of just sol=append(sol,temp).

Even though the fmt.Println(temp,append([]int{}, temp...)) statement generates the same output for temp and append([]int{}, temp...), use append([ The corrected version of ]int{}, temp...) actually works. Can someone explain the difference between temp and append([]int{}, temp...) in this case? Why does the corrected version work but the initial version doesn't?

Expectedtemp is the same as append([]int{},temp...)


Correct answer


sol =append(sol, temp) The problem is that you are adding the slice temp to the sol instead of the item "inside" the slice. As stated in the Slice internal blog post, a slice is "just" a pointer to an array, its length and capacity.

So, in your case, since temp is reused in each iteration, the array contents under the temp slice will be overwritten, and The values ​​inside the slice you previously added to sol will also be overwritten as modified (because the array under the slice has been modified). This is why you end up with wrong results, even though your fmt.Println statement appears before appending temp with the correct value.

When append([]int{}, temp...) creates a new slice, the value within the new slice cannot change because it is not reused.

The above is the detailed content of Strange behavior of append in Go. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template