1 回答
TA贡献1827条经验 获得超4个赞
可以在 中找到更新版本的 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 instance2
Copy(instance1).To(instance2)
- 1 回答
- 0 关注
- 155 浏览
添加回答
举报