怎么会这样?我该检查什么?
我的递归函数 visit(board) 接收一个结构体,在函数内部叫 incoming。
nextBoard 中有 left 和 right 两个切片。每个切片包含一些小的 cell 结构体,其成员是 label1、label2 和 bool。
visit(incoming) 里面有这些代码,
nextBoard := advance(incoming)
savedInput := incoming
visit(nextBoard)
函数内部没有其他调用 visit 的地方。
背景就是这些,问题是这样,假设 visit 在递归深度 27 被调用后,又向下走了 12 层。然后它返回深度 27。这时 incoming 的内容与调用前不同。奇怪的是 savedInput 也变了,而且和 incoming 的变化完全一样。nextBoard 仍然保持调用前的内容。
我想知道的是,这怎么可能?这 3 个变量的作用域都在函数内部,而不是包级别。
再补充一下 incoming 的变化,left 和 right 两个切片的 len 都是 7。right 切片返回后,第 7 个元素与原来不同了?
我确实知道,在深度 27 到 39 之间的某处,right 的第七个元素被替换成 left 的第七个元素,布尔值取反,同时 left 的第 7 个元素被删掉。这个修改由 advance(incoming) 函数完成。
更准确地说,incoming 返回深度 27 时,left 没有变化,而 right 有上面说的修改,也就是 right[6]=left[6] 并把布尔值取反。
我怀疑切片中的切片仍然指向与原对象共享的内存。这似乎是 incoming 和 savedInput 出现相同变化的唯一解释。但为什么调用后 incoming 会有任何变化呢?
谢谢花时间读完这些。
有什么特别需要检查的吗?我是不是误解了写下 savedInput:=incoming 的效果?我试过 :=,也试过先声明 savedInput 再用 =。
从英语翻译·查看原文How is this possible? What ought I check?
My recursive function visit(board) receives a struct, named incoming within the function.
nextBoard holds two slices left and right. Each slice contains small structs cell with components label1, label2 and bool.
Inside visit(incoming) I have:
nextBoard := advance(incoming)
savedInput := incoming
visit(nextBoard)
There are no other calls to visit inside it.
That is the background, now the problem: suppose at recursion depth 27 visit gets called, descending a further 12 levels. It then comes back to depth 27. Now incoming differs from its contents before that call. Oddly savedInput has changed too, in precisely the way incoming has. nextBoard still contains what it did before calling.
What I want to know is how? These 3 variables all have function scope, NOT scope at package level.
Some extra detail on incoming's changes: both left and right slices have len 7. Its right slice comes back with the 7th element changed from what it originally contained?
I do know that somewhere from depths 27 to 39, right's seventh element is replaced with left's seventh element, with its boolean reversed, and left loses its 7th element. A function named advance(incoming) performs that modification.
More precisely, when incoming comes back to depth 27, left is unchanged but right has the modification described above ie right[6]=left[6] with its boolean reversed.
My suspicion is that slices within slices still refer to memory shared with the original. It looks like the only reason incoming and savedInput would show identical modifications. Yet why would incoming differ at all after that call?
Thanks for taking the time to read this.
Is there a particular thing I should check? Am I misunderstanding the effect of writing savedInput:=incoming ? I've tried := as well as = with savedInput declared beforehand.