在使用Go语言的范围(range)时,向切片(slice)添加数据。

huangapple go评论80阅读模式
英文:

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{&quot;item-1&quot;, &quot;item-2&quot;, &quot;item-3&quot;}
	for i := 0; i &lt; len(slices); i++ {
		item := slices[i]
		if item == &quot;item-2&quot; {
			slices = append(slices, &quot;item-5&quot;)
		}
		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.

huangapple
  • 本文由 发表于 2022年12月7日 11:21:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/74711399.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定