For Loops in Go: Explained with Examples

One of the most common forms of control flow statements used to specify iteration, for loops are found in a wide range of programming languages. They are used to repeat a certain block of code a predefined known number of times.

For example, if you wanted to get the times of the first 40 trains from a timetable, you could use the for loop to repeat a function from 1 - 40 to get these values.

The Basic for loop in Go

The go programming language has only one looping concept, and this is the for loop. while loops, which are often found in other programming languages are also written with the for syntax in Go.

As in other programming languages, for loops in go have three main components all separated by semi-colons.

for initialization; condition; post {
  statement(s)
}
  • the initialization statement: this is executed before the first iteration of the loop takes place and is generally used to initialize variables that are used within the for loop
  • the condition expression: this is evaluated before every iteration; the for loop continues to execute as long as the condition specified here is met
  • the post statement: this is executed at the end of every run of the loop

Let's see this in example!

// Program to print the first 10 positive integers
func main() {
  // for loop terminates when i becomes 11
  for i := 1; i <= 10; i++ {
    fmt.Println(i)
  }
}

Here,

  • i := 1 is our initialization statement. We're using this to declare and initialize our variable, i.
  • i <= 10 is our condition expression. Here, the for loop will keep executing for as long as the value of i is less than or equal to 10.
  • i++ is our post statement and is executed after every iteration. Here, this means that after each run the value of i will increase by 1.

The variables that are initialized in the first, initialization statement are scoped to within the for loop. The scope is signified by the immediate curly braces.

Notice that while other programming languages tend to have parentheses around the for loop condition statement, go omits these

Implementing Infinite Loops with for

If an infinite loop is what you wish to have, go makes this really easy. The way to do it is to use the for keyword with open and closed curly braces and no initialization, expression, or update statements.

func main() {
	for {
    	// Do something forever
        }
}

Using continue and break to skip and terminate for loops

The break statement in Go is used to stop the current iteration of the for loop prematurely. This is usually paired with an if conditional statement to trap certain edge cases and terminate out of a loop earlier than planned.

func main() {
	for i := 0; i < 5; i++ {
		if i == 3 {
			fmt.Println("Terminating loop")
			break // break here
		}
        fmt.Println("Current value:", i)
	}
}

// Output
Current value: 0
Current value: 1
Current value: 2
Terminating loop
Here, the loop will stop executing when the value of i reaches 9

The continue statement is used when you want to skip the current iteration of your loop. Using continue in the middle of an iteration of the for loop will skip everything that follows and jump to the next iteration of the loop.

Just like break, this is also usually accompanied by a conditional if statement.

func main() {
	for i := 0; i < 5; i++ {
		if i == 2 {
			fmt.Println("Skipping")
			continue // break here
		}
		fmt.Println("Current value:", i)
	}
}

// Output
Current value: 0
Current value: 1
Skipping
Current value: 3
Current value: 4

The for loop is a powerful concept in any programming language and forms one of the most fundamental building blocks of learning how to code - in Go and otherwise!