HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
sliceoverreverseiteratewaythere

Problem

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

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


Edit: I asked this question a long time ago, it is 2022 now and the generic solution by @Ivan below seems like the way to go!

Solution

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

Code Snippets

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

Context

Stack Overflow Q#13190836, score: 246

Revisions (0)

No revisions yet.