Why the function append in Go work with reference when pass a slice? -


in next code i'm trying add element of slice of slices, go works reference, how can use using b slice value?

package main  import (     "fmt" )  func main() {     := []int{1}     arr := [][]int{a}      b := []int{2}      arr = append(arr, b)     fmt.println(arr)      b[0] = 3     arr = append(arr, b)         fmt.println(arr) } 

i expected last println [[1] [2] [3]], it's [[1] [3] [3]].

there no way insert slice "by value"; need make copy of slice before inserting it:

package main  import (     "fmt" )  func copy_ints(c []int) []int {     s := make([]int, len(c))     copy(s, c)     return s }  func main() {     := []int{1}     arr := [][]int{copy_ints(a)}      b := []int{2}      arr = append(arr, copy_ints(b))     fmt.println(arr)      b[0] = 3     arr = append(arr, copy_ints(b))      fmt.println(arr) } 

https://play.golang.org/p/tds5fgj3nf


Comments