Sobes.tech
Senior

What are the potential pitfalls when using the append method for a slice?

sobes.tech AI

Answer from AI

When using the append function for slices in Go, there are several important points that can lead to unexpected behavior:

  1. Modifying the underlying array: If the slice has enough capacity, append will add elements to the existing array, modifying it. This can affect other slices referencing the same array.

  2. Data movement during expansion: If there isn't enough capacity, append will create a new array and copy the data into it. In this case, the returned slice will point to the new array, and the old one remains unchanged. Forgetting to assign the result of append back will result in lost changes.

  3. Incorrect use of the append result: Always assign the result of append back to the slice variable, for example:

slice = append(slice, elem)

If you don't do this, the slice remains unchanged, and the new array will be lost.

  1. Concurrent access: append is not thread-safe, so when using slices concurrently, synchronization must be applied.

Example:

a := []int{1, 2, 3}
b := a[:2]
a = append(a, 4)
// b may unexpectedly change if `append` causes reallocation of the array

Therefore, it is always important to use the value returned by append and to keep in mind that the underlying array may change or be replaced.