In the next code I'm trying to add an element of a slice of slices, but as Go works with reference, how can I use this by using the b slice by value?
package main
import (
"fmt"
)
func main() {
a := []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 that the last Println was [[1] [2] [3]], but it's [[1] [3] [3]].
There is no way to insert a slice "by value"; you need to make a copy of the 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() {
a := []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)
}