猿问

复制一个结构体

我正在尝试在 go 中制作结构的深层副本。在自己去构建解决方案之前,我试图在 go 中找到惯用的方法。我确实找到了对这个实现的引用。但是,它似乎已经过时并且没有得到积极维护。我确信这是人们不时需要的场景,所以我一定会遗漏一些东西。有人有任何指导吗?


qq_花开花谢_0
浏览 156回答 1
1回答

GCT1015

可以在 中找到更新版本的 google deepcopy 代码margnus1/go-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{}) {我确定这是人们不时需要的场景,所以我一定错过了一些东西如本主题所述:例如,传递结构值而不是结构指针通常就足够了。如果程序员足够优秀,可以有效地设计树或图结构,那么他们可能会预料到共享这种结构时会出现问题。我们中的许多人都认为一个功能没有强制性的深度复制行为,因为我们希望 Go 提供有助于安全的工具,而不是提高效率的障碍。一个更新和完善的 deepcopy 版本是 ulule/deepcopier// Deep copy instance1 into instance2Copy(instance1).To(instance2)
随时随地看视频慕课网APP

相关分类

Go
我要回答