gpt4 book ai didi

arrays - 如何在 Go 中使用带有 for 循环的列表

转载 作者:行者123 更新时间:2023-12-03 02:23:31 27 4
gpt4 key购买 nike

我想将数字附加到列表中,但我的 slice 仅在 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 中有些东西我没有发现

最佳答案

您不存储 append() 的结果在你的“原创”slice ,因为您使用 short variable declaration而不是assignment :

slice := append(slice, i)

简短的变量声明(因为它与原始 slice 变量位于不同的 block 中)创建一个新变量(隐藏外部 slice ),并在循环内打印这个新变量多变的。因此,每次追加的结果仅在循环体内可见,并在迭代结束时丢失。而是使用赋值:

slice = append(slice, i)

但是,当你这样做时,你会得到一个无限循环,因为你的循环条件是 i < len(slice) ,和slice每次迭代都会增长。

相反,你应该这样做(评估 len(slice) 一次并存储它):

for i, length := 0, len(slice); i < length; i++ {
slice = append(slice, i)
fmt.Println(slice)
}

输出将是(在 Go Playground 上尝试):

[5 4 3 2 1 0]
[5 4 3 2 1 0 1]
[5 4 3 2 1 0 1 2]
[5 4 3 2 1 0 1 2 3]
[5 4 3 2 1 0 1 2 3 4]
[5 4 3 2 1 0 1 2 3 4]

请注意,如果您使用for range,您将得到相同的结果,因为这只对 slice 求值一次:

for i := range slice {
slice = append(slice, i)
fmt.Println(slice)
}

Go Playground 上试试这个.

关于arrays - 如何在 Go 中使用带有 for 循环的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58412911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com