Hurry! Try our new Interactive Courses for FREE. 🥳   🚀

Loops in Go

The for statement exists in Go to repeat a body of statements a specified number of times and one pass through the body is called an iteration. It should be noted that the repetition of the body statements can either be based on a counter or on a condition in Go.

In Go, we have only one looping construct. The for construct is the only construct that is used in Go for all types of loops. The basic for loop in Go looks pretty much the same as when compared to the for loops present in C or Java, with the only difference being that in Go we don't have the opening and the closing parentheses in the for loop.

It should also be noted that there is no do-while loop in Go, it was excluded as the developers claimed that the use case of such loop is not that much.

Types of for loops

In Go, there are two methods to control the loop iteration:

  • Counter-controlled iteration
  • Condition-controlled iteration

We will discuss both these approaches in this article with the help of examples.

Counter-controlled iteration

In this method of controlling the loop, we iterate over the loop with a set counter that can either be terminated in two manners, either we ascend towards the counter, or we descend towards it.

The simplest form of this counter-controlled iteration is shown in the code below.

for initialization; condition; modification { }

Example: For loop in Go

A very simple example of this approach is shown below, where we are iterating over the items of an array and then calculating the sum of all the elements with the help of the for loop which is counter-controlled.

package main

import (
	"fmt"
)

func main() {
	var arr = [5]int{1, 2, 3, 4, 5}
	var sum int
	for i := 0; i < len(arr); i++ {
		sum += arr[i]
	}
	fmt.Println("The Sum is:", sum)
}


The Sum is: 15

In the above example, we can see that we are trying to iterate over all the elements of the array, and at each iteration, we are trying to add the current element to the sum variable. The body {} of the for-loop is repeated a known number of times, this is counted by a variable i.

The loop starts with an initialization for i as i:=0(shorthand declaration). Then the declaration is followed by a conditional check on i < len(arr), which is performed before every iteration. When the condition evaluates to true, the iteration is done. Otherwise, the for-loop stops when the condition doesn't evaluate to true. Then following the condition, we have the modification of i, which is i++, which is performed after every iteration, at which point the condition is checked again to see if the loop can continue. This modification could, for example, also be a decrement, or + or -, using a step.

Let's explore one more example of the for loop where we will change the modification and only consider the elements that are present at even indices.

Example 2: For loop in Go

Consider the example shown below.

package main

import (
	"fmt"
)

func main() {
	var arr = [6]int{1, 2, 3, 4, 5, 6}
	var sum int
	for i := 1; i < len(arr); i += 2 {
		sum += arr[i]
	}
	fmt.Println("The Sum is:", sum)
}


The Sum is: 12

As we can see, that in the above for loop example, we are skipping the immediate next element and only considering the elements that are placed at even indices.

Example: For loop without paranthesis in Go

It should also be noted that if we try to use parentheses in the for loop statement, then it will throw an error.

Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	var arr = [6]int{1, 2, 3, 4, 5, 6}
	var sum int
	for (i := 1; i < len(arr); i += 2) {
		sum += arr[i]
	}
	fmt.Println("Sum is:", sum)
}


prog.go:10:9: expected ')', found ':=' (and 1 more errors)

Example: For loop with multiple counter

We can also use more than 1 counter in a for loop.

package main

import (
	"fmt"
)

func main() {
	var arr = [6]int{1, 2, 3, 4, 5, 6}
	var sum int
	var res [6]int
	for i, j := 0, 0; i < len(arr); i, j = i+1, j+1 {
		sum += arr[i]
		res[j] = sum
	}
	fmt.Println("The Sum is:", sum)
	fmt.Println("res arr:", res)
}


The Sum is: 21
res arr: [1 3 6 10 15 21]

Example: Nested Loop in Go

For loops can also be nested. A nested loop is a loop that in turn contains a loop inside it. Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	var arr = [3]int{1, 2, 3}
	for i := 0; i < len(arr); i++ {
		for j := 0; j < len(arr); j++ {
			fmt.Println("i and j are:", i, j)
		}
	}
}


i and j are: 0 0
i and j are: 0 1
i and j are: 0 2
i and j are: 1 0
i and j are: 1 1
i and j are: 1 2
i and j are: 2 0
i and j are: 2 1
i and j are: 2 2

In the above example, for every iteration of i, j will run three times, as the length of the array is 3. This means that the outer loop: for i:=0;i<len(arr);i++ will run three times and inner loop: j:=0;j<len(arr);j++ will run 9 times in total.

That is all about the counter-controlled loops, it's time to focus on another type of loop in Go.

Condition-controlled iteration loop

These types of for loops are a bit easier and less complicated than the counter-controlled loops, as there is only one constraint to either start the loop or break it, and that is the condition.

for condition { }

Let's explore an example of the for loop which follows the above syntax.

package main

import (
	"fmt"
)

func main() {
	cond := true
	for cond {
		fmt.Println("Inside")
		cond = false
	}
	fmt.Println("Loop Done")
}


Inside
Loop Done

Example: Infinite Loop in Go

In Go, we can create an infinite loop with the help of the above syntax, either we can omit the condition totally or we can simply tell the condition to be true and then do not change it inside the loop, which will make it act as an infinite loop.

Consider the example shown below:

package main

import (
	"fmt"
)

func main() {
	cond := true
	for cond {
		fmt.Println("Inside")
	}
	fmt.Println("Loop Done")
}


timeout running program
Inside
Inside
Inside
Inside
Inside
Inside
.
.
.

Conclusion

In this article, we learned about the two types of for loops that are present in Go along with several examples, we also learned about what keywords to use and syntax to follow, and what not to. In the last example, we learned about an infinite loop which is something that we should try to avoid as much as possible.