在golang中深拷贝具有指向0值的结构体。

huangapple go评论86阅读模式
英文:

Deepcopying struct having pointer-to 0 value in golang

问题

我有一个在golang中的结构体,如下所示:

type Test struct {
    prop *int
}

prop是指向零值的指针时,我想要对结构体对象进行深拷贝。实际的结构体中还有很多其他字段,我想要对整个结构体对象进行深拷贝。我尝试使用gob的编码-解码方式,但由于设计的后果,它会将指向0的指针转换为nil指针,详见这里。我还尝试使用reflect.Copy,但它会引发错误panic: reflect: call of reflect.Copy on struct Value。有没有更好的方法来深拷贝这样的结构体对象?

编辑:
我尝试使用json编码/解码,它似乎可以工作。但我不知道它的缺点。

func DeepCopy(a, b interface{}) {
    byt, _ := json.Marshal(a)
    json.Unmarshal(byt, b)
}

对于这个解决方案有什么意见吗?

英文:

I have a struct in golang as below

type Test struct {
    prop *int
}

I want to take deepcopy of the struct object when prop is pointer-to zero value. The real struct has lot more fields in it and I want deepcopy of entire struct obj. I tried to use gob encode-decode way but it converts pointer-to 0 to nil pointer due to consequence of the design as mentioned here. I also tried to use reflect.Copy but it panics with error panic: reflect: call of reflect.Copy on struct Value. Is there a better way to deepcopy such struct objects?

EDIT:
I tried to use json encoding/decoding and it kind of worked. But I don't know its drawbacks.

func DeepCopy(a, b interface{}) {
	byt, _ := json.Marshal(a)
	json.Unmarshal(byt, b)
}

Any comments on this solution?

答案1

得分: 1

我使用了https://github.com/mohae/deepcopy/blob/master/deepcopy.go作为示例。
reflect.Copy只适用于切片或数组。
正如你所看到的,使用反射是正确的方法,但它比简单调用reflect.Copy更复杂。还有一些其他的包实现了深拷贝,但我对这些包没有任何经验。

英文:

https://play.golang.org/p/fVKW62BYDm

I used https://github.com/mohae/deepcopy/blob/master/deepcopy.go for the example.
reflect.Copy only works for slices or arrays.
As you can see, using reflection is the right way, but it is more complex than simply calling reflect.Copy. There are a few other packages, that implement a deep copy, but I don't have any experience with any of those packages.

答案2

得分: 0

截至目前,我正在使用JSON编码/解码解决方案,并且它运行良好。

func DeepCopy(a, b interface{}) {
    byt, _ := json.Marshal(a)
    json.Unmarshal(byt, b)
}

我听说可能的缺点有:

  • 它有点慢
  • 在结构体中使用JSON标签
  • 只复制公共成员

但是目前没有任何问题影响到我。所以在我找到比这更好的解决方案之前,我将把这个设为答案。

英文:

As of now, I am using the json encoding/decoding solution and it is working well.

func DeepCopy(a, b interface{}) {
	byt, _ := json.Marshal(a)
	json.Unmarshal(byt, b)
}

I heard the possible disadvantages are:

  • it is kind of slow
  • uses json-tags in struct
  • only copies public members

But none of them are affecting me right now. So I am setting this as answer until I get anything better solution than this.

huangapple
  • 本文由 发表于 2017年8月24日 16:51:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/45857095.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定