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

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

for _, element := reverse range mySlice {
        ...
}

Solution 1:

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])
}

Solution 2:

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