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

后端 未结 7 1622
猫巷女王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:54

    No there is no convenient operator for this to add to the range one in place. You'll have to do a normal for loop counting down:

    s := []int{5, 4, 3, 2, 1}
    for i := len(s)-1; i >= 0; i-- {
       fmt.Println(s[i])
    }
    

提交回复
热议问题