开发者

Add data to slice when use range with go

开发者 https://www.devze.com 2022-12-07 21:19 出处:网络
I wanna append some data when range the slice, like this: package main import "fmt" func main() {

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消