dtnbjjq51949 2019-02-16 11:12 采纳率: 0%
浏览 28
已采纳

如何深度复制对象

This question already has an answer here:

I have a complex data structure, which defines a type P, and I'd like to perform a deep copy of an instance of such a data structure. I have found this library but, considering the semantics of the Go language, wouldn't a method like the following be more idiomatic?:

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

Since the method receives a value of type P (and values are always passed by copy), the result should be a reference to a deep copy of the source, like in this example:

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

Indeed,

src != dst => true
reflect.DeepEqual(*src, *dst) => true
</div>
  • 写回答

1条回答 默认 最新

  • duangeli1334 2019-02-16 11:24
    关注

    this test shows that your method doesn't do a copy

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 如何将下列的“无限压缩存储器”设计出来
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口