如何进行深拷贝对象



i具有复杂的数据结构,该数据结构定义了类型 p ,我想执行此类数据结构实例的深层副本。我找到了这个库,但是考虑到GO语言的语义,以下方法不会更惯用吗?:

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

由于该方法接收到类型 p 的值(并且始终按复制传递),因此结果应是对源的深副本的引用,例如在此示例中:

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

确实,

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

此测试表明您的方法不做副本

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

最新更新