如何深度复制对象

时间:2019-02-16 11:12:36

标签: go deep-copy

我有一个复杂的数据结构,它定义了一个 P 类型,我想对这种数据结构的实例进行深层复制。 我发现this library,但是考虑到Go语言的语义,像下面这样的方法难道不是惯用语吗?:

func (receiver P) copy() *P{
   return &receiver
}

由于该方法接收的值类型为 P (且值始终通过副本传递),因此结果应为对源深层副本的引用,如本例所示:

src := new(P)
dcp := src.copy()

的确,

src != dst => true
reflect.DeepEqual(*src, *dst) => true

1 个答案:

答案 0 :(得分:2)

此测试表明您的方法没有执行复制操作

package main

import (
    "fmt"
)

type teapot struct {
   t []string
}
type P struct {
   a string
   b teapot
}

func (receiver P) copy() *P{
   return &receiver
}

func main() {

x:=new(P)
x.b.t=[]string{"aa","bb"}
y:=x.copy()

y.b.t[1]="cc"  // y is altered but x should be the same

fmt.Println(x)  // but as you can see...

}

https://play.golang.org/p/xL-E4XKNXYe

相关问题