这看起来很奇怪,循环中有一个局部变量slice
为每个循环分配新值,我将该切片附加到全局sliceWrappers
。循环完成后,全局切片内的所有值仅包含对该局部切片变量上设置的最后一个值的引用。
Code:
package main
import (
"fmt"
"strconv"
)
func main() {
var sliceWrappers [][]string
initialSlice := append([]string{}, "hi")
initialSlice = append(initialSlice, "there")
// Remove this line and it works fine
initialSlice = append(initialSlice, "I'm")
for i := 0; i < 2; i++ {
slice := append(initialSlice, strconv.Itoa(i))
fmt.Printf("Slice Value : %+v, Initial Value : %+v\n", slice, initialSlice)
sliceWrappers = append(sliceWrappers, slice)
}
for _, sliceWrapper := range sliceWrappers {
fmt.Printf("%+v\n", sliceWrapper)
}
}
实际输出:
Slice Value : [hi there I'm 0], Initial Value : [hi there I'm]
Slice Value : [hi there I'm 1], Initial Value : [hi there I'm]
[hi there I'm 1]
[hi there I'm 1]
预期输出:
Slice Value : [hi there I'm 0], Initial Value : [hi there I'm]
Slice Value : [hi there I'm 1], Initial Value : [hi there I'm]
[hi there I'm 0] <------ This is not happening
[hi there I'm 1]
如果我删除initialSlice = append(initialSlice, "I'm")
线,然后就可以完美运行了。
Slice Value : [hi there 0], Initial Value : [hi there]
Slice Value : [hi there 1], Initial Value : [hi there]
[hi there 0] <------ Works Perfectly
[hi there 1]
我相信这与append
append 内置函数将元素追加到切片的末尾。
如果有足够的容量,目的地将被重新分割为
容纳新元素。
如果上述情况是造成这种情况的原因,那么不应值initialSlice
循环内打印的内容也与slice
?
操场 - https://play.golang.org/p/b3SDGoA2Lzv
PS:不幸的是,我为我的代码编写了仅 3 层嵌套的测试用例,并且顺利通过。我现在必须照顾copy对于循环内的切片。