我正在尝试克隆/复制html Node,以便我可以对其进行修改/复制,然后将其重新插入到主文档中。问题是我出现了堆栈溢出[2]。我认为存在比赛条件。看起来好像是Parent
和PrevSibling
字段(基于我的盲测)。知道为什么会这样,如何将其完全克隆(以便可以在reflect.DeepEqual上测试为阳性)?
func clone(src *html.Node) *html.Node {
if src == nil {
return nil
}
n := html.Node{
Parent: clone(src.Parent),
FirstChild: clone(src.FirstChild),
LastChild: clone(src.LastChild),
PrevSibling: clone(src.PrevSibling),
NextSibling: clone(src.NextSibling),
Type: src.Type,
DataAtom: src.DataAtom,
Data: src.Data,
Namespace: src.Namespace,
}
for _, v := range n.Attr {
n.Attr = append(n.Attr, v)
}
return &n
}
[2]
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow
runtime stack:
runtime.throw(0x3495b9, 0xe)
/Users/x/gosrc/src/runtime/panic.go:566 +0x95
runtime.newstack()
/Users/x/gosrc/src/runtime/stack.go:1061 +0x416
runtime.morestack()
/Users/x/gosrc/src/runtime/asm_amd64.s:366 +0x7f
goroutine 7 [running]:
runtime.heapBitsSetType(0xc42a0ae5b0, 0x70, 0x68, 0x32e420)
/Users/x/gosrc/src/runtime/mbitmap.go:867 fp=0xc4402002a8 sp=0xc4402002a0
runtime.mallocgc(0x70, 0x32e420, 0x1, 0x0)
/Users/x/gosrc/src/runtime/malloc.go:690 +0x5ba fp=0xc440200348 sp=0xc4402002a8
runtime.newobject(0x32e420, 0x0)
/Users/x/gosrc/src/runtime/malloc.go:785 +0x38 fp=0xc440200378 sp=0xc440200348
bitbucket.org/x/y/client.clone(0xc420138d20, 0x0)
最佳答案
当深克隆包含不是树的指针的数据结构时,您需要一种更复杂的方法。如果你打电话
n := Node{...
next:clone(src.next),
prev:clone(src.prev),
...}
并且您的结构甚至只有两个兄弟节点
n1
和n2
,其中n1.next
是&n2
,而n2.prev
是&n1
,该代码将堆栈溢出(克隆n1
将为clone(n2)
指针调用next
,然后又将clone(n1)
用作prev
指针,循环循环并向后循环直到调用堆栈爆炸)。一种解决方案是保留一个“高速缓存”,在其中克隆节点时,您将存储
src→cloned
关联,因此,在使用递归结构的情况下,克隆过程将能够返回该节点。以下是一个完整的最小示例:
package main
import "fmt"
type Node struct {
value int
prev, next *Node
}
func clone(n *Node, cache map[*Node]*Node) *Node {
if n == nil {
return nil
}
if val, ok := cache[n]; ok {
return val
}
val := &Node{}
cache[n] = val
val.value = n.value
val.prev = clone(n.prev, cache)
val.next = clone(n.next, cache)
return val
}
func printlist(n *Node) {
for n != nil {
println(fmt.Sprintf("address=%p, value=%v, prev=%p, next=%p",
n, n.value, n.prev, n.next))
n = n.next
}
}
func main() {
n1 := &Node{}
n2 := &Node{}
n3 := &Node{}
n1.value = 100
n2.value = 200
n3.value = 300
n1.next = n2
n2.prev = n1
n2.next = n3
n3.prev = n2
printlist(n1)
println("Cloning list")
c1 := clone(n1, make(map[*Node]*Node))
printlist(c1)
}
我在我的机器上运行此程序
~/x$ go run recstruct.go
address=0xc42000e540, value=100, prev=0x0, next=0xc42000e560
address=0xc42000e560, value=200, prev=0xc42000e540, next=0xc42000e580
address=0xc42000e580, value=300, prev=0xc42000e560, next=0x0
Cloning list
address=0xc42000e5c0, value=100, prev=0x0, next=0xc42000e5e0
address=0xc42000e5e0, value=200, prev=0xc42000e5c0, next=0xc42000e600
address=0xc42000e600, value=300, prev=0xc42000e5e0, next=0x0
~/x$
在这里,您可以看到三个节点已正确克隆,并且prev/next在克隆的结构列表中彼此指向。
关于go - 克隆节点[golang.org/x/net/html] : Stack overflow,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42611806/