Home > Software engineering >  Add data to slice when use range with go
Add data to slice when use range with go

Time:12-07

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.

CodePudding user response:

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.

  •  Tags:  
  • go
  • Related