Is there a way to iterate over a slice in reverse in Go?

后端 未结 7 1621
猫巷女王i
猫巷女王i 2021-01-30 15:28

It would be convenient to be able to say something like:

for _, element := reverse range mySlice {
        ...
}
7条回答
  •  佛祖请我去吃肉
    2021-01-30 15:58

    You can also do:

    s := []int{5, 4, 3, 2, 1}
    for i := range s {
            fmt.Println(s[len(s)-1-i]) // Suggestion: do `last := len(s)-1` before the loop
    }
    

    Output:

    1
    2
    3
    4
    5
    

    Also here: http://play.golang.org/p/l7Z69TV7Vl

提交回复
热议问题