1

I'm wondering about the following behavior:

sl1 := []int{0, 1, 2, 3, 4, 5}
fmt.Printf("sl1: %v\n", sl1)
//Prints sl1: [0 1 2 3 4 5]

idx := 3
sl2 := append(sl1[:idx], sl1[idx+1:]...)
fmt.Printf("sl1: %v\n", sl1)
//Prints sl1: [0 1 2 4 5 5] -> strange!
fmt.Printf("sl2: %v\n", sl2)
//Prints sl2: [0 1 2 4 5] -> expected!

Looks like append is doing something weird on the original slice pointer. Is this a bug or intended behavior? See also https://play.golang.org/p/EX3eqJz5Q8K

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

7

A slice consists of a reference to an underlying array, a length, and a capacity (maximum length). sl1[:idx] is a different slice than sl1 (the length is 3 instead of 6), but the underlying array is the same. The append places elements 4 and 5 of sl1 into the array at positions 3 and 4. sl2 is then a slice of length 5, but the underlying array is still the original one referenced by sl1, so when you print sl1, you see that the elements have changed. See https://blog.golang.org/go-slices-usage-and-internals for an explanation of how slices work.

Andy Schweig
  • 6,597
  • 2
  • 16
  • 22