Go gotcha: Why doesn't append work every time?

What's up with the append function?

a := []byte("Answer: ")

a1 := append(a, '1')
a2 := append(a, '2')

fmt.Println(string(a1))
fmt.Println(string(a2))
Answer: 2
Answer: 2
Answer

If there is room for more elements, append reuses the underlying array. Let's take a look:

a := []byte("Answer: ")
fmt.Println(len(a), cap(a)) // 8 32

This means that the slices a, a1 and a2 will refer to the same underlying array in our example.

To avoid this, we need to use two separate byte arrays:

const answer = "Answer: "

a1 := append([]byte(answer), '1')
a2 := append([]byte(answer), '2')

fmt.Println(string(a1)) // Answer: 1
fmt.Println(string(a2)) // Answer: 2

See Append function explained for more about the built-in append function in Go.

Comments

Be the first to comment!