Go 复制一个结构

Go 复制一个结构,go,Go,我正在尝试在go中制作结构的深度副本。在自己动手构建解决方案之前,我试图在go中找到实现这一点的惯用方法。我确实找到了关于实施的参考资料。然而,它似乎已经过时,没有积极维护。我相信这是一个人们经常需要的场景,所以我肯定错过了一些东西。有人有任何指导吗?可以在中找到google deepcopy代码的最新版本 它确实说明了为什么标准库中没有deepcopy // basic copy algorithm: // 1) recursively scan object, building up a l

我正在尝试在go中制作结构的深度副本。在自己动手构建解决方案之前,我试图在go中找到实现这一点的惯用方法。我确实找到了关于实施的参考资料。然而,它似乎已经过时,没有积极维护。我相信这是一个人们经常需要的场景,所以我肯定错过了一些东西。有人有任何指导吗?

可以在中找到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.
all算法非常复杂,依赖于反射。当然,只能访问导出字段

// 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{}) {

我相信这是一个人们经常需要的场景,所以我肯定错过了一些东西

作为:

例如,传递结构值而不是结构指针通常就足够了。如果程序员能够有效地设计树或图形结构,那么他们可能会预料到共享这种结构的问题。
我们中的许多人认为没有强制性的深度复制行为的特点,因为我们想提供工具,以帮助安全,而不是效率障碍。
deepcopy的一个更新、更完善的版本是


a:=b
?深度复制结构是什么意思?struct?标准库中的深度复制指针不包含深度复制功能,因为在应用程序执行此操作的方式上存在许多变化。此外,应用程序实现特定的复制功能并不困难。你要复印什么?
// Deep copy instance1 into instance2
Copy(instance1).To(instance2)