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?
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:
But none of them are affecting me right now. So I am setting this as answer until I get anything better solution than this.