Loops are an important concept in programming, and Go has several options for looping through code. Unlike other programming languages, Go only has one keyword to create a loop: for
.
That doesn’t mean Go has just one type of loop, though. In this article, we’ll explore four ways of looping in Go: for
loops, while
loops, infinite loops, and looping over a range.
The syntax of a Go for loop
One type of loop in Go is the for
loop. It closely resembles the traditional for-loop that those with experience in C-like languages will know. It has three parts:
- the init statement,
- the condition,
- and the post statement.
The init statement runs at the beginning of the loop, the condition is checked before each iteration, and the post statement runs at the end of each iteration. Here’s an example:
for i := 0; i < 5; i++ {
fmt.Println(i)
}
Code language: Go (go)
This loop will print out the numbers 0 through 4.
Did you recognize the three parts?
- The variable
i
is initialized to 0 in the init statement - The loop continues as long as
i
is less than 5 (the condition) - At the end of each iteration,
i
is incremented by 1 using the post statementi++
.
A Go While Loop
Another type of loop in Go is the while
loop, which only has a condition checked at the beginning of each iteration. If the condition is true, the loop continues; if it is false, it ends. Let’s see how we can create the equivalent of a while loop using for
:
x := 0
for x < 5 {
fmt.Println(x)
x++
}
Code language: Go (go)
This loop will also print out the numbers 0 through 4. The variable x
is initialized to 0 before the loop, and the loop continues as long as x
is less than 5. At the end of each iteration, x
is incremented by 1.
Infinite loop
To create an infinite loop in Go, use for without anything else:
for {
....
}
Code language: Go (go)
You’ll have to break out of the loop yourself, e.g. when some condition is met. To do so, you can use either:
break
: a statement created to break out of loops immediatelyreturn
, which returns from the function this loop is currently running ingoto
, which jumps to a labeled section of code.
Go range loops
Finally, there’s also a range
form of the for
loop in Go, which iterates over a slice or map. Here’s an example:
numbers := []int{1, 2, 3, 4, 5}
for i, number := range numbers {
fmt.Println(i, number)
}
Code language: Go (go)
This loop will print out the index and value of each element in the numbers
slice. The variable i
is the current element’s index, and number
is the value of the element.
Learn more
Here are some more resources to learn about loops:
- The Go documentation has a section on loops that provides more information and examples: https://tour.golang.org/flowcontrol/1
- The Go by Example website has several examples of different types of loops in Go: https://gobyexample.com/looping