The for loop is a control flow statement used to repeatedly execute a block of code. In Go, the for loop is the only looping construct.

You can use the for loop to repeat blocks of code and simulate a full range of loops from other languages, including for...each, while loops, and do...while loops.

Install Go to Begin

Make sure you have Go installed to follow along. Most of these examples require the fmt package, and you should use an overall structure like this:

        package main
 
import "fmt"
 
func main() {
    // code goes here
}

A Three-Component for Loop in Go

This is perhaps the most common for loop. As the name suggests, it takes three components: the initial value, a condition, and a post statement. Here is the syntax:

        for initialization; condition; post {
    statement(s)
}

In this loop, after the initialization, the condition is evaluated. If true, the statements in the for loop block execute, followed by the post statement. The program repeats this process until the condition no longer evaluates to true. Below is an example.

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

Here:

  • the initialization sets i to 1
  • the condition is i <= 5
  • the post statement is i++

This for loop prints the current value of i if it is less than or equal to 5. The ‘post statement’ adds 1 to i after each loop and once i gets to 5, the loop terminates. Without the ‘post statement’, the loop would execute infinite times and potentially cause the program to crash.

A For-Each Loop in Go

Go does not have a for-each loop, but you can modify a for loop to traverse a collection of elements. Here is the syntax:

        for index, value := range collection {
    // body
}

The collection can be an array, slice, string or map, or values received on a channel. The index is the position in the collection. The value is the element at the index.

If you only care about the value, omit the index like this:

        for _, value := range slice {}

In the example below, the loop traverses the array and prints both the index and the value of each item in it.

        array := []string{"hello", "world"}
 
for i, j := range array {
    fmt.Println(i, j)
}

A While Loop in Go

You can use the for loop to achieve while loop functionality. In a while loop, a statement runs so long as a condition remains true. Consider the following:

        i := 1
 
for i <= 5 {
i *= 2
}
 
fmt.Println(i)

In this code, while i is less than or equal to 5, it is multiplied by 2 each time the loop runs.

A Do…While Loop in Go

The do...while loop is different from the while loop as the loop body will execute at least once. There are two approaches to implementing this in Go.

  1. Ensure the condition for the first iteration is set to true.
            i := 10
     
    for next := true; next; next = i <= 5 {
        fmt.Println(i)
        i++
    }
     
    // Will print 10
    Since the initial condition is set to true, i is printed and then incremented in the first iteration. Since the condition (i <=5) evaluates to false during the second iteration, the loop exits.
  2. Execute the loop body once before checking the condition.
            i := 10
     
    for {
        fmt.Println(i)
        i++
        
       if i >= 5 {
            break;
        }
    }
     
    // Will print 10
    In the for loop above, 10, which is the value of i is printed first then the if statement executes. If the condition is true, the loop breaks, otherwise the loop continues.

Other Control Flow Statements

Loops in programming are important because they simplify repetitive tasks, and save time. Instead of writing a line of code ten times, you can simply create a loop that runs ten times. Other control flow statements are if, if...else, if...else if...if, and switch statements.