Go Language: Understanding and Using For Loops

Go programming language provides a way to execute a code block repeatedly using the for loop statement. In Go, for loops can be used in several ways, making it a versatile and powerful feature for developers. This article will review the various forms of for loops in Go and how to use them effectively.

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 the Go language, we can run for-loop only and no while-loops.

Let’s look at the various kind of for loops one by one.

A simple for loop
Syntax for a simple 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 optional and will be discussed 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 is optional.
for loop in golang
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 was executed, assigning the variable value 1.
  2. Then, the condition expression will be evaluated, so we checked whether i <= 3 ( i was less than or equal to 3). Here i value equals 1, so it passed the condition and moved on to execute the for-loop block.
  3. Then it executed the code within the for-loop block. In our case, it just printed the variable value.
  4. Next, it executes 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

Golang supports the infinite for loop, and we can achieve this in several ways.

Way – 1

We can run an infinite loop by removing all three 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, 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 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
for loop with continue keyword

The continue statement can skip the current iteration of a for loop and move on to the next iteration.

Skipping the whole for-loop block using the continue keyword

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

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

Here, 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.

for loop with the break keyword

There might be some scenarios where we must get out of the loop when encountering a certain condition. This can be achieved 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.

Golang for…range loop

Go provides us with an easy way 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 element’s index.
  • value variable will hold the actual value of the array’s elements.
  • arrayName is the array that we want to run a 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 the 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 write us in the comments or mail us at admin@codekru.com.

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *