Important Characteristics of Go: Loops

Let’s learn about iterations with for loops and the range keyword.

Iterating with for loops and the range keyword

This lesson is all about iterating in Go. Go supports for loops as well as the range keyword for iterating over all the elements of arrays, slices, and maps. An example of Go’s simplicity is the fact that Go only provides support for the for keyword instead of including direct support for while loops. However, depending on how we write a for loop, it can function as a while loop or an infinite loop. Moreover, for loops can implement the functionality of JavaScript’s forEach function when combined with the range keyword.

Note: We need to put curly braces around a for loop, even if it contains a single statement or no statements at all.

We can also create for loops with variables and conditions. A for loop can be exited with a break keyword, and we can skip the current iteration with the continue keyword. When used with range, for loops allow us to visit all the elements of a slice or an array without knowing the size of the data structure. for and range allow us to iterate over the elements of a map in a similar way.

Coding example

The following program forLoops.go illustrates the use of for on its own and with the range keyword.

Get hands-on with 1200+ tech skills courses.