我有一個復雜的數據結構,它定義了一個類型P,我想對這種數據結構的一個實例進行深度復制。我找到了這個庫,但是,考慮到 Go 語言的語義,像下面這樣的方法不會更慣用嗎?:func?(receiver?P)?copy()?*P{
??return?&receiver
}由于該方法接收類型P的值(并且值始終通過副本傳遞),因此結果應該是對源的深層副本的引用,如本例所示:src?:=?new(P)
dcp?:=?src.copy()的確,src?!=?dst?=>?true
reflect.DeepEqual(*src,?*dst)?=>?true
1 回答

狐的傳說
TA貢獻1804條經驗 獲得超3個贊
此測試表明您的方法不執行復制
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
- 1 回答
- 0 關注
- 118 瀏覽
添加回答
舉報
0/150
提交
取消