How to use reverse loops in Golang

Overview

Carrying out a backward loop can be very useful irrespective of the language we use. In this shot, we will use Golang to carry out an iteration in the reverse direction.

Note: Golang has only one looping construct, the for loop.

Example

The code below explains how to use a reverse loop in Golang:

package main
import "fmt"
/* For exercises uncomment the imports below */
// import "strconv"
// import "encoding/json"
func main() {
myList := []int{5,4,3,2,1}
for index := len(myList)-1; index >= 0; index-- {
fmt.Println(myList[index])
}
}

Example explained

  • Line 2: We import the fmt package, which we use for our output’s print.

  • Line 7: We create a list named myList and then assign values to it.

  • Line 8: In our for loop, we initialize the variable index with the index of myList's last element len(myList)-1. We then move towards the first element where index will be 0. We use index-- to continue looping from the end to the beginning.

  • Line 9: We print our list named myList.

Free Resources