The for Construct
Explore the for construct in Go to understand how to implement counter-controlled and condition-controlled loops. Learn to write nested loops and handle string iterations, including issues with Unicode strings, preparing you for advanced Go control structures.
We'll cover the following...
Introduction
So far, we have studied two types of constructs; the if-else and the switch construct. Another very important and widely used control structure in programming is the for construct.
In Go, the for statement exists to repeat a body of statements a number of times. One pass through the body is called an iteration.
Remark: There is no
formatch for thedo-whilestatement found in most other languages. It was probably excluded because the use case for it was not that important.
Types of for loops
There are two methods to control iteration:
- Counter-controlled iteration
- Condition-controlled iteration
Let’s study them one by one.
Counter-controlled iteration
The simplest form is the counter-controlled iteration. The general format is:
for initialization; condition; modification { }
For example:
for i := 0; i < 10; i++ {}
The body { } of the for-loop is repeated a known number of times; this is counted by a variable i. The loop starts with an initialization for i as: i := 0 ( this is performed only once). This is shorter than a declaration beforehand, and it is followed by a conditional check on i: i < 10, which is performed ...