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
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