How to Iterate Over a Slice in Reverse in Go
Created
Modified
Using For Loop
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.
See the following example:
package main
import (
"fmt"
)
func main() {
s := []string{"a", "b", "c", "d"}
for i := len(s) - 1; i >= 0; i-- {
fmt.Println(s[i])
}
}
d c b a
Using For Range
You can also do:
package main
import (
"fmt"
)
func main() {
s := []string{"a", "b", "c", "d"}
l := len(s)
for i := range s {
fmt.Println(s[l-1-i])
}
}
d c b a