0
package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4, 5}
    b := append(a[:3], 6, 7)
    fmt.Println("a is ", a)
    fmt.Println("b is ", b)
}

The above program prints

a is [1, 2, 3, 6, 7]
b is [1, 2, 3, 6, 7]

I understand the output of b. But why did slice a change? Shouldn't a[:3] create a new anonymous slice and append 6,7 and return that to b instead of changing the original(a) slice? Why did append act on the original slice?

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
ramesh
  • 21
  • 3

2 Answers2

2

NOTICE append function will create new slide if your slice is not sufficient (overflow). See difference between two examples:

func main() {
a := []int{1, 2, 3, 4, 5}
b := append(a[:3], 6, 7) // add 2 elements, not overflow slice, doesnt create new slice
fmt.Println("a is ", a)
fmt.Println("b is ", b)
}

result

a is [1, 2, 3, 6, 7]
b is [1, 2, 3, 6, 7]

And

func main() {
a := []int{1, 2, 3, 4, 5}
b := append(a[:3], 6, 7, 8) // add 3 elements, overflow slice, create new slice
fmt.Println("a is ", a)
fmt.Println("b is ", b)
}

Result

a is  [1 2 3 4 5]
b is  [1 2 3 6 7 8]
Sơn xê kô
  • 179
  • 1
  • 4
2

I slightly modified your program to make it more clear

package main

import "fmt"

func main() {
    a := []int{1, 2, 3, 4, 5}
    b := a[:3] // Here Slicing does not copy the slice's data. It creates a new slice value that points to the original array
    b = append(b, 6, 7)
    fmt.Println("a is ", a)
    fmt.Println("b is ", b)
}

Refer this Document for more reading !!

Arun
  • 1,651
  • 4
  • 20
  • 31
  • I request everyone to refer @sơn-xê-kô 's answer too, to understand a different nature of slice , that too relevant !!, – Arun Jun 24 '20 at 05:28