How To Iterate Over A Range Of Integers In Go (Goalng)

In Go (Golang) the for construct is the only keyword used to declare loops, as opposed to other programming languages where we could use while. There are a couple of ways we can use the for construct in Go (Golang). Let’s see the various examples and example of the for’s syntax

for <init statement>; <condition expression>; <post statement> {
      // do stuff here...
}    

The init statement is executed before the first iteration, the condition expression is evaluated after each iteration and the post statement is executed after each iteration.

How to iterate over a range of integers?

We know the basics and how easy is to use the for loop in Go (Golang), let’s see how we can iterate over a range of integers in Go, for example from 1 to 9

for i:=0; i < 10; i++ {
      fmt.Println(i)
}     

Like you would do in any other languages, iterating over a range of integers is straightforward in Go.

Or you alternatively you could use the range construct and range over an initialised empty slice of integers

for i := range [10]int{} {
        fmt.Println(i)
}       
Join the Golang Developers Community on Golang Cafe