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

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

Add data to slice when use range with go

问题

我想在遍历切片时添加一些数据,就像这样:

  1. package main
  2. import "fmt"
  3. func main() {
  4. slices := []string{"item-1", "item-2", "item-3"}
  5. for _, item := range slices {
  6. if item == "item-2" {
  7. slices = append(slices, "item-5")
  8. }
  9. fmt.Println(item)
  10. }
  11. }

代码输出:

  1. item-1
  2. item-2
  3. item-3

我期望的输出是:

  1. item-1
  2. item-2
  3. item-3
  4. item-5

在Go语言中,可以使用以下方式实现类似Python中的语法:

  1. slices := []string{"item-1", "item-2", "item-3"}
  2. for _, item := range append(slices[:0:0], slices...) {
  3. if item == "item-2" {
  4. slices = append(slices, "item-5")
  5. }
  6. fmt.Println(item)
  7. }

希望对你有所帮助!

英文:

I wanna append some data when range the slice, like this:

  1. package main
  2. import "fmt"
  3. func main() {
  4. slices := []string{"item-1", "item-2", "item-3"}
  5. for _, item := range slices {
  6. if item == "item-2" {
  7. slices = append(slices, "item-5")
  8. }
  9. fmt.Println(item)
  10. }
  11. }

the code output:

  1. item-1
  2. item-2
  3. item-3

I expect:

  1. item-1
  2. item-2
  3. item-3
  4. item-5

Similar to this syntax in python:

  1. slices = ["item-1", "item-2", "item-3"]
  2. for item in slices[::]:
  3. if item == "item-2":
  4. slices.append("item-5")
  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

  1. func main() {
  2. slices := []string{"item-1", "item-2", "item-3"}
  3. for i := 0; i < len(slices); i++ {
  4. item := slices[i]
  5. if item == "item-2" {
  6. slices = append(slices, "item-5")
  7. }
  8. fmt.Println(item)
  9. }
  10. }

因为你在循环中重新赋值了slices,所以你需要在每次迭代中重新检查len以查看当前的长度。内置的range只会迭代slices的初始值;它不会看到在迭代过程中对slice定义进行的任何更新。

英文:

Instead of using range, iterate explicitly with a counter

  1. func main() {
  2. slices := []string{&quot;item-1&quot;, &quot;item-2&quot;, &quot;item-3&quot;}
  3. for i := 0; i &lt; len(slices); i++ {
  4. item := slices[i]
  5. if item == &quot;item-2&quot; {
  6. slices = append(slices, &quot;item-5&quot;)
  7. }
  8. fmt.Println(item)
  9. }
  10. }

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:

确定