RockyMountainHigh
RockyMountainHigh

Reputation: 3021

Make a copy of a struct

I am attempting to make a deep copy of a struct in go. Before going and building a solution myself, I attempted to find the idiomatic way to do so in go. I did find reference to this implementation. However, it appears to be well out of date and not actively maintained. I'm sure this is a scenario that people much require from time-to-time so I must be missing something. Does anybody have any guidance?

Upvotes: 1

Views: 2982

Answers (1)

VonC
VonC

Reputation: 1327064

A more recent version of the google deepcopy code can be found in margnus1/go-deepcopy.

It does illustrate why there is no deepcopy in the standard library.

// basic copy algorithm:
// 1) recursively scan object, building up a list of all allocated
// memory ranges pointed to by the object.
// 2) recursively copy object, making sure that references
// within the data structure point to the appropriate
// places in the newly allocated data structure.

The all algo is quite convoluted and rely on reflection. And of course only access exported field.

// Copy makes a recursive deep copy of obj and returns the result.
//
// Pointer equality between items within obj is preserved,
// as are the relationships between slices that point to the same underlying data,
// although the data itself will be copied.
// a := Copy(b) implies reflect.DeepEqual(a, b).
// Map keys are not copied, as reflect.DeepEqual does not
// recurse into map keys.
// Due to restrictions in the reflect package, only
// types with all public members may be copied.
//
func Copy(obj interface{}) (r interface{}) {

I'm sure this is a scenario that people much require from time-to-time so I must be missing something

As mentioned in this thread:

Passing struct values as opposed to struct pointers, for example, is generally good enough. If the programmer is good enough to effectively design tree or graph structures, then they can probably anticipate problems with sharing such a structure.
Many of us consider the absence of mandatory deep-copy behavior to a feature, since we want Go to provide tools to aid safety, not obstacles to efficiency.


A more recent and polished version of deepcopy is ulule/deepcopier

// Deep copy instance1 into instance2
Copy(instance1).To(instance2)

Upvotes: 1

Related Questions