我正在尝试在 go 中制作结构的深拷贝。在自己构建解决方案之前,我试图在 go 中找到惯用的方法。我确实找到了对 this 的引用执行。但是,它似乎已经过时并且没有得到积极维护。我敢肯定这是人们不时需要的场景,所以我一定遗漏了一些东西。有人有任何指导吗?
最佳答案
可以在 margnus1/go-deepcopy
中找到更新版本的 google deepcopy 代码.
它确实说明了为什么标准库中没有 deepcopy。
// 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.
所有算法都非常复杂并且依赖于反射。当然,只能访问导出的字段。
// 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
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.
deepcopy 的更新和完善版本是 ulule/deepcopier
// Deep copy instance1 into instance2
Copy(instance1).To(instance2)
关于go - 复制一个结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628099/