Loop Statements in Go

Loop Statements in Go

In this tutorial, we are going to discuss loop statements in the Go language. A loop is a code structure that loops around to repeatedly execute a piece of code, often until some condition is met.

Using loops in computer programming allows us to automate and repeat similar tasks multiple times. For example, if you want to count the number of lines in the file, you can use a loop in your code.

Loop Statements in Go

For is the only loop available in the Go language. Go language doesn’t have while or do-while loops present in other languages like C and Java.

The while loop is missing from go, but a while loop can be implemented using a for loop, as we will see later in this tutorial.

for loop in GO has three parts as shown below in the format

  • initialization part
  • condition part
  • post part

Syntax

for initialization; condition; post {
}

The initialization statement will be executed only once. After the loop is initialized, the condition will be checked. If the condition evaluates to true, the body of the loop inside the {} will be executed, followed by the post statement.

The post statement will be executed after each successful iteration of the loop. After the post statement is executed, the condition will be rechecked. If it’s true, the loop will continue executing; else the for loop terminates.

All the 3 components namely initialization, condition and post are optional in Go language. Let’s look at an example to understand for loop better.

package main

import (
    "fmt"
)

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Printf(" %d",i)
    }
}

Output

 1 2 3 4 5

Run in playground

In the above example, i is initialized to 1. The conditional statement will checks if i <= 5. If the condition is true, the value of i is printed, else the loop is terminated. The post statement increments i by 1 at the end of each iteration. Once i become greater than 5, the loop terminates.

Please note that the variables declared in a for loop are only available within the loop’s scope. Hence i cannot be accessed outside the body for loop.

break

When a break statement is encountered inside a loop, the loop is immediately terminated, and the program control resumes at the next statement following the loop.

package main

import (
     "fmt"
)

func main() {
    for i := 1; i <= 5; i++ {
        if i > 3 {
           break
        }
        fmt.Printf("%d ", i)
    }
    fmt.Println("\nline after for loop")
}
1 2 3  
line after for loop

Run in playground

continue

The continue statement is used to skip the current iteration of the for loop. After the continue statement, all code present in a for loop will not be executed for the current iteration. The loop will move on to the next iteration.

package main

import (  
    "fmt"
)

func main() {  
    for i := 1; i <= 20; i++ {
        if i%2 == 0 {
            continue
        }
        fmt.Printf("%d ", i)
    }
}

Output

1 3 5 7 9 11 13 15 17 19 
Nested for loops

A for loop which has another for loop inside it is called a nested for loop. These can be useful when you want to have a looped action performed on every data set element.

package main

import (
    "fmt"
)

func main() {
    n := 5
    for i := 0; i < n; i++ {
        for j := 0; j <= i; j++ {
            fmt.Print("*")
        }
        fmt.Println()
    }
}

Output

* 
** 
*** 
**** 
*****

Run in playground

Note

  • The parenthesis is not necessary around for loop, but the curly braces around the body are necessary.
  • The init and post part is optional.
  • The init part can be any statement with a short declaration, function call, or assignment. If the init part has the variable declaration, then the scope of that variable is limited to within the for loop.
  • The post part can be any statement but generally contains the increment logic. The post part cannot contain initialization. The compiler will raise an error in case we add any initialization logic to the post part.
For loop with only condition
package main

import "fmt"

func main() {
	i := 0
	for i < 5 {
		fmt.Println(i)
		i++
	}
}

Output

0
1
2
3
4

Run in playground

For Infinite loop
package main

import (
	"fmt"
	"time"
)

func main() {
	i := 0
	for {
		fmt.Println(i)
		i++
		time.Sleep(time.Second * 1)
	}
}

Output

0
1
2
3
4
5
.
.

Run in playground

Implementing while loop using for loop

Go doesn’t have the while keyword. Instead, it has the for keyword only. However, for keyword can be used to simulate the functionality same as while.

for loop can be implemented to behave the same as while if initialization part and increment part can be skipped. 

Here is an example

package main

import "fmt"

func main() {
	i := 1
	for i <= 5 {
		fmt.Println(i)
		i++
	}
}

Output

1
2
3
4
5

Run in playground

Loop Statements in Go
Scroll to top