Go has only for
loop, but itβs versatile.
Complete, C-style for
It has 3 statements: init, comparison and increment.
Variable in the init statements is scoped to the for
loop.
:=
is required in the init statement, var
is not legal here.
The init and post statements are optional:
Condition-only for
Similar to while
loops in other languages.
Infinite for
Range for
To iterate over a slice or a map range
form can be used. It returns two values: index and value (copy of the element at that index).
Use _
for either index or value if itβs not needed:
If only one value is specified, youβll get only the index:
Can iterate only over the built-in compound types and user-defined types that are based on them.
It iterates over copy, so the value canβt be changed in place:
Map order
Order of the iteration over a map is randomized each time to prevent developers relying on the specific order and to prevent Hash DoS attack. But when printing the map, Go outputs keys in the ascending order.
Strings
Iterating over strings has the same nuances described in Indexing. Go will iterate over runes in the string, not bytes, and will offset the index by the number of bytes, see example below:
break
and continue
Works similar to Python.
Can use labels to control what loop to target: