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
forloop.
Example
The code below explains how to use a reverse loop in Golang:
package mainimport "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
fmtpackage, which we use for our output’s print. -
Line 7: We create a list named
myListand then assign values to it. -
Line 8: In our
forloop, we initialize the variableindexwith the index ofmyList's last elementlen(myList)-1. We then move towards the first element whereindexwill be0. We useindex--to continue looping from the end to the beginning. -
Line 9: We print our list named
myList.