14

You can run the example code on Go Playground.

Here is the code:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    fmt.Println(numbers)
    _ = append(numbers[0:1], numbers[2:]...)
    fmt.Println(numbers)
}

Output:

[1 2 3 4 5]
[1 3 4 5 5]

Why was the numbers slice modified by append? Is this expected behavior and if yes, could you explain to me why? I thought append doesn't modify its arguments.

Christian Siegert
  • 1,545
  • 1
  • 12
  • 14
  • 1
    Did you read the [documentation](http://golang.org/ref/spec#Appending_and_copying_slices) on append? I think it explains the behavior pretty well. – fuz Jun 30 '13 at 22:23

1 Answers1

21

See http://blog.golang.org/go-slices-usage-and-internals.

The append function could allocate a new underlying array if what you are appending to the slice does not fit in the current slice's capacity. Append does modify the underlying array. The reason you have to assign back to the variable is because, as I said in the first sentence, the underlying array could be reallocated and the old slice will still point to the old array.

See this play example to see exactly what I am talking about.

twmb
  • 1,710
  • 1
  • 20
  • 18