简体   繁体   中英

Deepcopying struct having pointer-to 0 value in golang

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM