In this lesson, we learn about the for loop syntax for Golang and how to write for loop in Go.

Go is very simple and tries to minimize developer errors. For this, Go supports only one kind of loops and that is using for keyword. Go does not have while or do...while loop.

Syntax of For loop

Go syntax for the for loop looks like below.

1for initialization; check_condition; post_iteration {
2    ... ...
3}
4
5for i := 1; i <= 5; i++ {
6    fmt.Println(i)
7}

Here, we don’t need parentheses like we didn’t need for if condition checks. For loop contains three main items.

  1. Initilization of loop variable: This is where the loop variable gets initialized with start value.
  2. Condition: This is the condition which is checked after each iteration. If this condition is true, loop gets executed and when this condition becomes false, the loop terminates.
  3. Post Iteration statements: This is where we modify the loop variable so that this doesn’t result in infinite loop.

Let’s see an example of for loop.

For Loop Example

1package main
2
3import "fmt"
4
5func main() {
6	for i := 0; i < 5; i++ {
7		fmt.Println(i)
8	}
9}

Output:

0
1
2
3
4

We can also skip any of these statements. For example, in below code, this same for loop is working like a while loop which produces same result as above.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	i := 0
 7	for i < 5 {
 8		fmt.Println(i)
 9		i++
10	}
11}

If we omit certain statements, that will likely cause infinite loop. Below is an example of infinite loop which prints 0 forever.

1i := 0
2for {
3    fmt.Println(i)
4}

Continue statement

If we want to skip one of the iteration, we can use the continue keyword with a conditional and depending on the result of conditional evaluation, that iteration will be skipped. For example, below code skips iteration when i has odd value and hence it prints only even numbers.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	for i := 1; i <= 10; i++ {
 7		if i%2 != 0 {
 8			continue
 9		}
10		fmt.Println(i)
11	}
12}

Output:

2
4
6
8
10

Break Statement

Similarly, if we want loop to break out pre-maturely when certain condition holds true, we can use break keyword. In below code example, the loop breaks when we encounter first number which is divisible by 5.

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6	for i := 1; i <= 10; i++ {
 7		if i%5 == 0 {
 8			fmt.Println("Breaking out of loop when i is", i)
 9			break
10		}
11		fmt.Println(i)
12	}
13}

Output:

1
2
3
4
Breaking out of loop when i is 5

Go also supports goto statement although the usage of goto is highly discouraged. The goto keyword sends program flow to different location identified by a label without any conditions.