英文:
Add data to slice when use range with go
问题
我想在遍历切片时添加一些数据,就像这样:
package main
import "fmt"
func main() {
slices := []string{"item-1", "item-2", "item-3"}
for _, item := range slices {
if item == "item-2" {
slices = append(slices, "item-5")
}
fmt.Println(item)
}
}
代码输出:
item-1
item-2
item-3
我期望的输出是:
item-1
item-2
item-3
item-5
在Go语言中,可以使用以下方式实现类似Python中的语法:
slices := []string{"item-1", "item-2", "item-3"}
for _, item := range append(slices[:0:0], slices...) {
if item == "item-2" {
slices = append(slices, "item-5")
}
fmt.Println(item)
}
希望对你有所帮助!
英文:
I wanna append some data when range the slice, like this:
package main
import "fmt"
func main() {
slices := []string{"item-1", "item-2", "item-3"}
for _, item := range slices {
if item == "item-2" {
slices = append(slices, "item-5")
}
fmt.Println(item)
}
}
the code output:
item-1
item-2
item-3
I expect:
item-1
item-2
item-3
item-5
Similar to this syntax in python:
slices = ["item-1", "item-2", "item-3"]
for item in slices[::]:
if item == "item-2":
slices.append("item-5")
print(item)
How it should be implemented in Go?Thanks
i try to search in this website and google, use the Add data to slice when use range with go
keyword.
答案1
得分: 2
使用计数器显式迭代而不是使用range
func main() {
slices := []string{"item-1", "item-2", "item-3"}
for i := 0; i < len(slices); i++ {
item := slices[i]
if item == "item-2" {
slices = append(slices, "item-5")
}
fmt.Println(item)
}
}
因为你在循环中重新赋值了slices
,所以你需要在每次迭代中重新检查len
以查看当前的长度。内置的range
只会迭代slices
的初始值;它不会看到在迭代过程中对slice定义进行的任何更新。
英文:
Instead of using range
, iterate explicitly with a counter
func main() {
slices := []string{"item-1", "item-2", "item-3"}
for i := 0; i < len(slices); i++ {
item := slices[i]
if item == "item-2" {
slices = append(slices, "item-5")
}
fmt.Println(item)
}
}
Because you re-assign slices
in the loop, you need to re-check the len
every iteration to see how long it is currently. The built-in range
only iterates over the initial value of slices
; it doesn't see any updates to the slice definition that happen during iteration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论