Guide to golang for loop ( Loops in Go language )

In this post, we are going to discuss the Golang for loop in detail.

Loop is used to run a block of code repeatedly. So, if we have some code or statements that need to be executed repeatedly, we will place them inside a loop. In Go language, we can run loops using for-loop only.

Syntax for a simple golang for loop
for initialization ;condition expression ; post statement {
   // code within the for loop block
}

A for loop usually have three parts

  • Initialization – An initialization statement is an optional statement in for loop which will be discussing later in the post. The initialization statement or init statement is usually used to initialize a variable.
  • Condition expression – This is a boolean expression that will be evaluated at each iteration of the loop. If this expression evaluates to true, then the loop will continue to execute and if it evaluates to false, then the loop will be terminated.
  • Post statement – The post statement is executed after each iteration of the for loop and it is also an optional statement.
for loop in golang

A simple for loop

package main

import "fmt"

func main() {

	for i := 1; i <= 3; i++ {
		fmt.Println("i = ", i)
	}

}

Output –

i =  1
i =  2
i =  3

So, what happened here?

  1. First, the initialization statement got executed, assigning variable value as 1.
  2. Then, the condition expression will be evaluated, so, here we checked whether i <= 3 ( i was less than or equal to 3 or not). Here i value is equal to 1, so, it passed the condition and moved on to execute the for-loop block.
  3. Then it excuted the code within the for-loop block. In our case it just printed the variable value.
  4. Next, it excutes the post statement. Here we used the increment operator, so, it will increase the variable value by 1. Now, the variable value will be 2.
  5. After executing the post statement, the code will go back to Step 2 and check the condition expression again, and thus the loop will continue till it fails the condition expression.

An infinite for loop

There are many ways to run an infinite loop in Golang. We will only be discussing some of them.

Way – 1

We can run an infinite loop by removing all three of the conditions or expressions from the for-loop.

package main

import "fmt"

func main() {

	for {
		fmt.Println("codekru in an infinite loop")
	}

}

Output –

codekru in an infinite loop
codekru in an infinite loop
codekru in an infinite loop
codekru in an infinite loop
codekru in an infinite loop
codekru in an infinite loop
codekru in an infinite loop
...........................
...........................
Way – 2

We can run an infinite loop by writing true in the condition expression. This will make the condition expression true no matter what the initialization statement or the post statement is.

package main

import "fmt"

func main() {

	for i := 3; true; i++ {
		fmt.Println("i = ", i)
	}

}

Output –

i =  3
i =  4
i =  5
i =  6
i =  7
......
......
Way – 3

We can make the post statement such that it never fails the expression condition placed on the for-loop. An example of the same is shown below.

package main

import "fmt"

func main() {

	for i := 3; i <= 5; i-- {
		fmt.Println("i = ", i)
	}

}

Output –

i =  3
i =  2
i =  1
i =  0
i =  -1
......
......

Here we initialized the variable from 3 while decrementing its value at each iteration using the post statement ( i– ). So, in the next iteration, the variable value will be 2, and then 1, and so on. It will never fail the condition set in the for-loop as i will always be less than or equal to 5 and thus the loop will never end.

for loop working as while loop

There is no while keyword in the Go language but we can surely use the Golang for-loop as a while-loop. To achieve this, we only have to write the condition expression in the for-loop statements and our for-loop will work as a while-loop.

Syntax to use for-loop as while-loop

package main

import "fmt"

func main() {

	i := 3

	for i <= 5 {
		fmt.Println("i = ", i)
		i++
	}

}

Output –

i =  3
i =  4
i =  5

Skipping iterations in a loop using continue keyword

We can skip some of the iterations of the loop based on some condition(s). We can either skip the whole for loop block or some part of it. Don’t worry, we will be showing both of them to you.

Skipping the whole for-loop block

To skip the whole loop, we have to place the condition at the start of the for loop as shown below

package main

import "fmt"

func main() {

	for i := 3; i <= 6; i++ {

		if i == 4 {
			continue
		}

		fmt.Println("Entering in for loop")

		fmt.Println("i =", i)

	}

}

Output –

Entering in for loop
i = 3
Entering in for loop
i = 5
Entering in for loop
i = 6

We can see here that i = 4 is not printed because that was skipped.

Skipping a part of the for-loop block

In this scenario, we will need to place the condition at a place from where we want to stop the execution of the loop for that particular iteration.

package main

import "fmt"

func main() {

	for i := 3; i <= 6; i++ {

		fmt.Println("Entering in for loop")

		if i == 4 {
			continue
		}

		fmt.Println("i =", i)

	}

}

Output –

Entering in for loop
i = 3
Entering in for loop
Entering in for loop
i = 5
Entering in for loop
i = 6

Here we can see that the “Entering in for loop” was printed 4 times, while the variable is printed only 3 times because we stopped the loop from executing further when i=4 and continued with the next iteration.

Breaking out of for loop using break keyword

There might be some scenarios where we will be needed to get out of the loop when encountered a certain condition. This can be achieved by using the break keyword within the if block as shown below

package main

import "fmt"

func main() {

	for i := 3; i <= 6; i++ {

		if i == 5 {
			break
		}

		fmt.Println("i =", i)

	}

}

Output –

i = 3
i = 4

Here, we can see that the for loop is meant to run till variable ( i ) values reach 6 but the code only printed up to 4. This is because we placed a condition at the start of the loop that whenever the variable value reaches 5, we will break out of the for-loop and this is what happened here.

Looping over arrays using for…range

Go provides us an easy of iterating over the elements of an array using the for…range loop.

Syntax of for…range

for index , value := range arrayName{
   // code within the for loop block
}
for range loop in golang

  • index variable will hold the elements’s index .
  • value variable will hold the actual value of the array’s elements.
  • arrayName is the array that we want to run loop on

The loop will run once for each element in the array, assigning the element’s index to the index variable and the element’s actual value to the value variable.

package main

import "fmt"

func main() {

	arr := [5]int{13, 20, 23, 43, 123}

	for index, value := range arr {
		fmt.Println(index, value)
	}

}

Output –

0 13
1 20
2 23
3 43
4 123

If you don’t intend to use the index variable anywhere in the program, then you can use the blank identifier in its place.

Important points to remember while using for loops

1) You might have noticed that we haven’t used the parentheses in the for loop anywhere like in many other languages. This is because Go language doesn’t allow them, so, if we try to write a for loop with parentheses, then it will throw us an error.

package main

import "fmt"

func main() {

	for (i := 1; i <= 3; i++) {
		fmt.Println("i = ", i)
	}

}

Output –

syntax error: unexpected :=, expecting )

2) Opening curly braces should be in the same line as that of the for keyword, as Go language doesn’t allow us to use the opening curly braces in the next line which many other languages support.

package main

import "fmt"

func main() {

	for i := 1; i <= 3; i++ 
	{
		fmt.Println("i = ", i)
	}

}

Output –

syntax error: unexpected newline, expecting { after for clause

Hope you liked the article. If you have any doubts or concerns, please feel free to write us in comments or mail us at [email protected]

Liked the article? Share this on

Leave a Comment

Your email address will not be published.