I want to clone a [][]float64 slice in Go without affecting the original array. How can I do it?
In the below example, I want the slice a1 to remain unaffected when a2 is changed. At present, I am using the built in append function of Go. But I have not been able to get the desired functionality.
package main
import (
"fmt"
)
func main() {
a1 := [][]float64{[]float64{1.0,1.0}, []float64{2.0,2.1}}
a2 := make([][]float64, len(a1))
a2 = append([][]float64{}, a1...)
fmt.Println(a2, a1) // At this step, a1 has not changed.
a2[1][0] = 5.0 //Change value of one element of a2.
fmt.Println(a2, a1) // At this step, a1 has changed.
}
>> [[1 1] [2 2.1]] [[1 1] [2 2.1]]
>> [[1 1] [5 2.1]] [[1 1] [5 2.1]]
When I use copy function of Go, I find that it supports int datatype. I get the following error when I use the copy function. Understandably, the below error is because of Type mismatch between what copy expects in Go.
cannot use copy(a2, a1) (type int) as type [][]float64 in assignment
I want to use slices and not arrays.
I am using this reference. I am new to Go and will appreciate any help.