如何深层复制对象[重复]

问题描述 投票:-3回答:1

这个问题在这里已有答案:

我有一个复杂的数据结构,它定义了一个类型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
go deep-copy
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.