How do you copy the Item struct and all pointers to a new struct?
type Item struct {
A []*ASet `json:\"a,omitempty\"`
B []*BSet. `json:\
What you want is essentially a deep copy which is not supported by the standard library.
Your choices:
The last option could look like this:
var i1 Item
data, err := json.Marshal(i1)
if err != nil {
panic(err)
}
var i2 Item
if err := json.Unmarshal(data, &i2); err != nil {
panic(err)
}
// i2 holds a deep copy of i1
Note that marshaling/unmarshaling isn't particularly efficient, but easy and compact. Also note that this might not handle recursive data structures well, might even hang or panic (e.g. a field points to the containing struct), but handling recursive structures may be a problem to all solutions. Also note that this won't clone unexported fields.
The good thing about this marshaling / unmarshaling is that you can easily create a helper function to deep-copy "any" values:
func deepCopy(v interface{}) (interface{}, error) {
data, err := json.Marshal(v)
if err != nil {
return nil, err
}
vptr := reflect.New(reflect.TypeOf(v))
err = json.Unmarshal(data, vptr.Interface())
if err != nil {
return nil, err
}
return vptr.Elem().Interface(), err
}
Testing it:
p1 := image.Point{X: 1, Y: 2}
fmt.Printf("p1 %T %+v\n", p1, p1)
p2, err := deepCopy(p1)
if err != nil {
panic(err)
}
p1.X = 11
fmt.Printf("p1 %T %+v\n", p1, p1)
fmt.Printf("p2 %T %+v\n", p2, p2)
Output (try it on the Go Playground):
p1 image.Point (1,2)
p1 image.Point (11,2)
p2 image.Point (1,2)