Go logo

What is for loop in Go?

A for loop is a repeat control structure that lets us write a loop that’s executed a particular number of times. The Go for loop is used for repeating a set of statements a number of times.

A few main points about Go for loop:

  • It’s the only available loop in Go language.
  • There are two variations of for loop in Go
  • 1- Counter-controlled iteration
  • 2- Condition-controlled iteration.
  • The while loop is not available but the for loop may act as a while loop (see an example later)
Structure of for loop

The general structure of for loop in Go language is:

for initialization; condition; post{

// statements to execute here

}

A simple example of for loop

In this example, we are using for loop to display numbers. The variable is initialized with a value=5 and it will display numbers till it reaches 15.

The code:

package main 

import "fmt" 

func main() { 

   for x := 5; x < 16; x++ { 

      fmt.Print(x,"\n") 

   } 

}

The output of the above code:

5

6

7

8

9

10

11

12

13

14

15

Using break statement with for loop

The break statement can be used inside a for loop that will terminate the loop and control goes at the next line outside the loop. An example of the break statement is shown below:

Further Reading:  The Variables in Go Programming

The code:

package main




import "fmt"


func main() {


 var x int = 5

   for x < 15 {

      fmt.Printf("%d\n", x);

      x++;

      if x > 10 {

         /* break will terminate as value reaches above 10 */

         break;

      }

   }

}

The output:

5

6

7

8

9

10

For loop with continue example

For moving to the next iteration, you may use the continue statement. See an example below:

package main




import "fmt"




func main() {




for x := 1992; x <= 2022; x++ {

 if x%4 != 0 {

continue

    

 }

 fmt.Println(x)

 }

   

}

 

The output is leap years from 1992 to 2022:

1992

1996

2000

2004

2008

2012

2016

2020

Using for loop as while loop example

The example below shows using for loop acting as a while loop (if you wonder where is while loop in the Go language?)

package main 

import "fmt" 

func main() { 

   x := 1 

   for x < 30 { 

      x += x 

      fmt.Println(x) 

   } 

}

The result:

2

4

8

16

32

A for example with map

You may also use a for loop to iterate over key/value pairs of a map. See this example:

package main


import "fmt"


func main() {


    Fmap := map[int]string{

        1:"Mike",

        2:"Qiado",

        3:"Diana",

    }

    for key, value:= range Fmap {

       fmt.Println(key, value) 

    }

   

}

 

Further Reading:  What is a pointer in Go Language?

Output:

1 Mike

2 Qiado

3 Diana