【发布时间】:2020-02-13 05:04:14
【问题描述】:
我想将数字附加到列表中,但我的切片仅在 for 循环中更新值。
如何在外面更新?
slice := []int{5,4,3,2,1}
for i := 0; i < len(slice); i++ {
slice := append(slice, i)
fmt.Println(slice)
}
fmt.Println(slice)
实际结果
[5 4 3 2 1 0]
[5 4 3 2 1 1]
[5 4 3 2 1 2]
[5 4 3 2 1 3]
[5 4 3 2 1 4]
[5 4 3 2 1]
预期结果
[5 4 3 2 1 0]
[5 4 3 2 1 1]
[5 4 3 2 1 2]
[5 4 3 2 1 3]
[5 4 3 2 1 4]
[5 4 3 2 1 0 1 2 3 4]
这段代码在 Python 中工作,但在 go 中有一些我没有捕捉到的东西
【问题讨论】:
-
循环内的
slice是block作用域
标签: arrays loops for-loop go slice