Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

People also ask

How do I loop through a string in Golang?

Iterate over Characters of String in Golang To iterate over characters of a string in Go language, we need to convert the string to an array of individual characters which is an array of runes, and use for loop to iterate over the characters.


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

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


Variation with index

for k := range s {
        k = len(s) - 1 - k
        // now k starts from the end
    }

How about use defer:

s := []int{5, 4, 3, 2, 1}
for i, _ := range s {
   defer fmt.Println(s[i])
}

One could use a channel to reverse a list in a function without duplicating it. It makes the code nicer in my sense.

package main

import (
    "fmt"
)

func reverse(lst []string) chan string {
    ret := make(chan string)
    go func() {
        for i, _ := range lst {
            ret <- lst[len(lst)-1-i]
        }
        close(ret)
    }()
    return ret
}

func main() {
    elms := []string{"a", "b", "c", "d"}
    for e := range reverse(elms) {
        fmt.Println(e)
    }
}

I guess this is the easiest way to reverse arrays.:

package main

import "fmt"

// how can we reverse write the array
func main() {

    arr := [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    revArr := [len(arr)]int{} // making empty array for write reverse

    for i := range arr {
        revArr[len(arr)-1-i] = arr[i]
    }

    fmt.Println(revArr)
}

https://play.golang.org/p/QQhj26-FhtF