18. For
Running Loops
For Statement
When we need to repeat things, that's where loops come into play. Unlike other programming languages, Go has only single construct for looping, for
Traditional loop
We can write traditional for loop using loop variable similar to most other programming languages.
for initialization; condition; post statement {
code to execute
}
For loop as while loop
We can only define the condition part in for loop and it will act like a while loop. We need to make sure initialization if any required as well as post conditioned are handled.
for condition { code to execute }
If we skip the line 4 above, we end up creating infinite loop.
Continue and Break
We can use continue and break statement inside of for loop to control flow. continue
is used to run next iteration of loop and abandon remaining code in current loop iteration. break
is used to break out of the loop.
The first for loop above will not print if value is even and continue to next iteration. Second for loop will break the loop when k reaches 13.
Infinite Loop
We can also skip condition part of for loop which will create infinite loop. Make sure there is way to break out of for loop when no condition is provided.
Iterating over range
Go can easily iterate over arrays,maps and slices using range
keyword.
When iterating over slice, range returns index and value from slice.
When iterating over maps, range returns key and value.
range is also useful for getting each rune from string.
Last updated