在Go中克隆浮动切片而不影响原始切片

Lin*_*Guo 6 arrays go slice

我想克隆一个[][]float64 sliceinGo而不影响原始数组。我该怎么做?

在下面的示例中,我希望切片在更改a1时保持不受影响。a2目前我使用的是Go内置的append函数。但我一直无法获得所需的功能。

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]]
Run Code Online (Sandbox Code Playgroud)

当我使用Go的复制功能时,我发现它支持int数据类型。当我使用复制功能时,出现以下错误。可以理解的是,下面的错误是因为 Go 中的 copy 期望的类型不匹配。

cannot use copy(a2, a1) (type int) as type [][]float64 in assignment
Run Code Online (Sandbox Code Playgroud)

我想使用切片而不是数组。

我正在使用这个参考。我是 Go 新手,非常感谢任何帮助。

rus*_*tyx 3

多维切片是切片的切片。如果是使用循环的 2D 切片,则必须单独克隆每个切片。

像这样的事情:

package main

import (
    "fmt"
)

func Clone(arr [][]float64) (res [][]float64) {
    res = make([][]float64, len(arr))
    for i := range arr {
        res[i] = append([]float64{}, arr[i]...)
    }
    return
}

func main() {
    a1 := [][]float64{{1.0, 1.0}, {2.0, 2.1}}
    a2 := Clone(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)
}
Run Code Online (Sandbox Code Playgroud)

印刷

[[1 1] [2 2.1]] [[1 1] [2 2.1]]
[[1 1] [5 2.1]] [[1 1] [2 2.1]]
Run Code Online (Sandbox Code Playgroud)