Loops in Go

In programming, loops are useful for iterating over a set of values or executing a block of code a certain number of times. Go doesn’t have a while keyword as in other languages. However, it does have a for loop and you can use it for all your looping needs.

In this post we explore how the for loop in Go can handle different looping scenarios.

While True

The syntax for creating a for loop that executes code while some condition is true is shown below. A conditional statement is evaluated before every iteration is run. The value x is printed and then incremented by one until the condition x <= 5 is no longer True.

package main

import "fmt"

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

The output is:

1
2
3
4
5

Loop Indefinitely

You can also create a for loop that runs indefinitely until some condition is met that breaks out of the loop. The following code snippet creates the same output as the example above but uses a slightly different syntax.

package main

import "fmt"

func main() {
	x := 1
	for {
		if x > 5 {
			break
		}
		fmt.Println((x))
		x += 1
	}
}

The difference with this method is that instead of evaluating a condition before the iteration is run, we check it in the middle of iteration. This could be useful in cases where we want a certain block of code within the loop to execute before deciding on whether to continue looping.

Loop Over Slices

Slices of data are something you will frequently want to loop through to parse data. An example of this is shown below.

package main

import "fmt"

func main() {
	icecream := []string{"Vanilla", "Chocolate", "Strawberry", "Mint Chocolate Chip", "Peppermint"}
	for i := 0; i < len(icecream); i++ {
		fmt.Println(icecream[i])
	}
}

Here, we have a slice of strings that we want to print to the console. We create a for loop with an init statement that sets i to 0, a condition that checks whether i is less than the length of the slice, and a post statement that increments i. We then print the element at index i.

The output is:

Vanilla
Chocolate
Strawberry
Mint Chocolate Chip
Peppermint

The Range Keyword

The range clause is another method for iterating over slices. It can also be used to loop over arrays, strings, maps, and so on.

Try out the following code snippet in your editor.

package main

import "fmt"

func main() {
	icecream := []string{"Vanilla", "Chocolate", "Strawberry", "Mint Chocolate Chip", "Peppermint"}
	for index, value := range icecream {
		fmt.Println(index, value)
	}
}

In this example, range returns an index and a value for each element in the icecream slice. We then print out each index value and string.

The output is:

0 Vanilla
1 Chocolate
2 Strawberry
3 Mint Chocolate Chip
4 Peppermint

But what if we don’t need or want the index for each value? We can use an underscore _ to effectively throw away that data.

Update the for loop with the following:

for _, value := range icecream {
	fmt.Println(value)
}

The output is:

Vanilla
Chocolate
Strawberry
Mint Chocolate Chip
Peppermint

Continue

The continue keyword in Go works the same as in other languages. It lets you skip over any remaining code in the current loop and continue to the next iteration.

Update the previous code with the following.

package main

import "fmt"

func main() {
	icecream := []string{"Vanilla", "Chocolate", "Strawberry", "Mint Chocolate Chip", "Peppermint"}
	for _, value := range icecream {
		if value == "Vanilla" {
			continue
		}
		fmt.Println(value)
	}
}

Inside the for loop, an if-statment is used to check whether the string contains the word “Vanilla” and if it does, the print statement is skipped and the next iteration begins. This effectively prevents the word “Vanilla” from being printed to the console.

Chocolate
Strawberry
Mint Chocolate Chip
Peppermint

Break

The break keyword is used to stop the entire for loop, the current iteration and any remaining ones, and continues on with the program.

Update the the previous for loop with the following.

for _, value := range icecream {
	if value == "Strawberry" {
		break
	}
	fmt.Println(value)
}

Now when we reach the string “Strawberry” the break statement ends the for loop with only the first two elements in the slice printed.

Vanilla
Chocolate

The break statement only breaks the current loop.

In the example below, we have nested for loops that would print the slice of ice cream flavors twice. However, the break statement breaks out of the inner loop after the first two flavors are printed. The outer loop continues with the next iteration, and the break statement breaks again after two flavors are printed.

package main

import "fmt"

func main() {
	icecream := []string{"Vanilla", "Chocolate", "Strawberry", "Mint Chocolate Chip", "Peppermint"}
	for i := 0; i < 2; i++ {
		for _, value := range icecream {
			if value == "Strawberry" {
				break
			}
			fmt.Println(value)
		}
	}
}

The output is:

Vanilla
Chocolate
Vanilla
Chocolate

Summary

In this post, we explored how the for loop is used in Go programming. You can loop a predetermined number of times, you can loop over a slice or a range of values, and you can loop indefinitely until some condition is met.

Check out the Go page for more lessons on programming with Go.