我正在尝试执行以下结构的深层复制:
// Ternary Tree
type Tree struct {
Left *Tree
Mid *Tree
Right *Tree
Value interface{}
Parent *Tree
Orientation string
IsTerminal bool
Type string
}
以下是我的遗憾尝试。看起来我正在根处创建一棵新树,但它的子树仍然指向内存中的相同地址。
func (tree *Tree) CopyTree() *Tree {
if (tree == nil) {
return nil
} else {
copiedTree := &Tree {
tree.Left.CopyTree(),
tree.Mid.CopyTree(),
tree.Right.CopyTree(),
tree.Value,
tree.Parent.CopyTree(),
tree.Orientation,
tree.IsTerminal,
tree.Type}
return copiedTree
}
}
Go 中是否有任何有用的构造可以帮助深度复制结构?如果没有,我将如何自己执行此深复制?请注意,“deepcopy http://godoc.org/code.google.com/p/rog-go/exp/deepcopy“ 包不再工作,因为它使用了一些在 Go 1 发布时已弃用的函数
我很接近。我应该将 CopyTree 分配给父属性。
func (tree *Tree) CopyTree() *Tree {
if (tree == nil) {
return nil
} else {
copiedTree := &Tree {
tree.Left.CopyTree(),
tree.Mid.CopyTree(),
tree.Right.CopyTree(),
tree.Value,
nil,
tree.Orientation,
tree.IsTerminal,
tree.Type,
}
if copiedTree.Left != nil {
copiedTree.Left.Parent = copiedTree
}
if copiedTree.Right != nil {
copiedTree.Right.Parent = copiedTree
}
if copiedTree.Mid != nil {
copiedTree.Mid.Parent = copiedTree
}
return copiedTree
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)