I thought append
in go, will return a new result, but I find that append in same slice will return same memory address:
func TestRuneAppend3(t *testing.T) {
r := make([][]rune, 256)
r[0] = append(r[0], 99) // c
r[1] = append(r[0], 100) // d
r[2] = append(r[0], 101) // e
// I thought it would be "c cd ce", but it is "c ce ce"
log.Println(string(r[0]), string(r[1]), string(r[2]))
}
So what is the best way if I want to the result is c cd ce
?
Append will only allocate a new array if there isn't sufficient capacity in the slice you're appending to. If you need to have a separate array, use make
to create a new slice and use copy
to copy whatever you need from the original slice.
This article gives a good explanation of how slices work.