unexpected slice append behaviour

前端 未结 3 1813
臣服心动
臣服心动 2021-02-06 12:58

I encountered weird behaviour in go code today: when I append elements to slice in loop and then try to create new slices based on the res

3条回答
  •  死守一世寂寞
    2021-02-06 13:18

    If you need a copy of a slice, there's no other way to do it other than, copying the slice. You should almost never assign the result of append to a variable other than the first argument of append. It leads to hard to find bugs, and will behave differently depending on whether the slice has the required capacity or not.

    This isn't a commonly needed pattern, but as with all things of this nature if you need to repeate a few lines of code multiple times, then you can use a small helper function:

    func copyAndAppend(i []int, vals ...int) []int {
        j := make([]int, len(i), len(i)+len(vals))
        copy(j, i)
        return append(j, vals...)
    }
    

    https://play.golang.org/p/J99_xEbaWo

提交回复
热议问题