In Go there is only one looping construct; the for loop. The for loop is very versatile and can be used to implement patterns such as: for, while, do while, and do until.
Iterating Over Arrays and Slices
Iterating over arrays, slices, and maps are done using the for loop. In Listing 3.2 the len function is used to return the length of the array, 4, so the for loop will stop when i reaches 4.
The "range" Keyword
Previously we used a "classic" for loop for iteration. Looping over collection types is common in Go that the language offers the range keyword to simplify this code.
Range returns the index and the value of each item in the array or slice. If only the index of the loop is needed, and not the value, using only a single variable in the for loop with range will return the index of each loop.
A lot of languages expose an interface, or similar mechanism, that can be implemented to allow for custom iterable types. Go does not provide any such interface. Only the built-in collection types, and a few other built-in types to be discussed later, are supported with the range keyword.
The continue keyword allows us to go back to the start of the loop and stop executing the rest of the code in the for block.
This does not stop the loop from executing, but rather ends that particular run of the loop.
To stop execution of a loop we can use the break keyword.
Using the continue and break keywords we can control a for loops execution to deliver the results we want.
Do While Loop
A do while loop is used in a situation where you want the loop to run at least 1 iteration, regardless of the condition.
A C/Java-style example would look something like Listing 3.8.
To create a do while style loop in Go a combination of an infinite loop and the break keyword can be used as in Listing 3.9.