dongpu1315 2015-07-13 09:59
浏览 93
已采纳

Golang:在切片上使用追加时出现问题

I am using golang. Here is my code:

func main() {
    quanPailie([]int{1, 2})
}

func quanPailie(nums []int) [][]int {
    COUNT := len(nums)

    //only one item
    if COUNT == 1 {
        return [][]int{nums}
    }

    insertItem(quanPailie(nums[:COUNT-1]), nums[COUNT-1])
    return [][]int{}
}

func insertItem(res [][]int, insertNum int) {
    fmt.Println("insertItem,res:", res, "insertNum", insertNum) //insertItem,res: [[1]] insertNum 2

    for _, v := range res {
        for i := 0; i < len(v); i++ {
            fmt.Println("===before,v:", v)
            c := append(v[:i], append([]int{insertNum}, v[i:]...)...)
            fmt.Println("===after,v:", v)

            fmt.Println("ccc", c)

        }
    }
}

What makes me very confused is the output:

===before,v: [1]
===after,v: [2]

Why did the value of v change? Hope someone can help me. Thanks a lot.

Go playground: https://play.golang.org/p/wITYsGpX7U

EDIT:
Thanks for icza's great help, I think I have understood this problem.
And, here is a simple code to show this issue.

func test1() {
    nums := []int{1, 2, 3}
    _ = append(nums[:2], 4)
    fmt.Println("test1:", nums)

    //nums changes because the cap is big enought, the original array is modified.

}

func test2() {
    nums := []int{1, 2, 3}
    c := append(nums[:2], []int{4, 5, 6}...)
    fmt.Println("test2:", nums)
    fmt.Println("cc:", c)

    //nums dont't change because the cap isn't big enought.
    //a new array is allocated while the nums still points to the old array.
    //Of course, the return value of append points to the new array.
}

Go playground: https://play.golang.org/p/jBNFsCqUn3

  • 写回答

1条回答 默认 最新

  • douxuelv7755 2015-07-13 10:40
    关注

    This is the code in question:

    fmt.Println("===before,v:", v)
    c := append(v[:i], append([]int{insertNum}, v[i:]...)...)
    fmt.Println("===after,v:", v)
    

    You ask why v changes between the 2 Println() statements.

    Because you are using the builtin append() function, quoting from its doc:

    The append built-in function appends elements to the end of a slice. If it has sufficient capacity, the destination is resliced to accommodate the new elements. If it does not, a new underlying array will be allocated. Append returns the updated slice.

    So if the slice you append to has enough room (capacity) to accomodate the elements you want to append, no new slice will be allocated, instead the destination slice will be re-sliced (which will use the same underlying array) and append will happen in that.

    Let's check the capacity:

    fmt.Println("===before,v:", v, cap(v))
    c := append(v[:i], append([]int{insertNum}, v[i:]...)...)
    fmt.Println("===after,v:", v, cap(v))
    

    Output:

    ===before,v: [1] 2
    ===after,v: [2] 2
    

    The v slice has a capacity of 2. When for loop starts, i=0, v[:i] is v[:0] which is an empty slice (but has capacity 2) and so appending 1 or 2 elements will not allocate a new array/slice, it will be done "in place". This "in place" is the 0th element of v, since v[:i] is shorthand for v[0:i]. Hence the elements will be appended starting from v[0] in the underlying array which is shared, so the element denoted by v[0] will change.

    Note that slicing a slice results in a slice which shares its underlying backing array with the original slice (does not make a copy of the elements).

    If you want to avoid this, use or allocate a new slice, copy original content and append to the new slice, e.g.:

    src := []int{1, 2}
    c := make([]int, len(src))
    copy(c, src)
    // Append something:
    c = append(c, 3, 4)
    
    fmt.Println(src) // [1 2] - src doesn't change
    fmt.Println(c)   // [1 2 3 4]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?