如何深拷贝对象
How to deep-copy objects
我有一个复杂的数据结构,它定义了一个类型 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
此测试表明您的方法没有进行复制
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...
}
我有一个复杂的数据结构,它定义了一个类型 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
此测试表明您的方法没有进行复制
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...
}