Go Loops
A loop statement allows the execution of a statement or group of statements multiple times. Go has a 'for' loop, for which there is a number of different variations, that will be discussed below.
Three-component loop
As the name suggests, this version of a 'for' loop has three components that forms its declaration, an initialiser, a condition, and a post statement.
for initialiser; condition; post { // Statement(s) to execute. }
The initialiser is usually a local variable set up as a loop counter. The condition is an expression that is checked before each iteration of the loop, which must evaluate to true for the statements within the loop to be executed. Finally, the post statement is an expression that is executed at the end of each loop, which usually increments the loop counter.
The following example outputs to the screen the value of the loop counter for each iteration of the loop.
for i := 0; i < 5; i++ {
fmt.Println(i)
}
Here the initialiser is set to zero and the condition is checking for a value of less than five. With the post statement adding one to the loop counter each time, it means that the statements within the loop will be executed five times. The output from this loop is shown below.
0 1 2 3 4
While loop
The 'while' variation of a 'for' loop has a condition, which must evaluate to true before the statements within it can be executed.
for condition { // Statement(s) to execute. }
In the below example, a variable is declared and initialised to zero, then the loop checks to see that the variable is less than five before outputting it to the screen and incrementing the variable by one.
i := 0
for i < 5 {
fmt.Println(i)
i++
}
The output is the same as the previous example.
Infinite loop
An infinite 'for' loop has no condition at the point of entry. This loop will continue to execute indefinitely unless a statement is used to explicitly break out of the loop.
for { // Statement(s) to execute. }
Here, a variable is declared and initialised to zero. The loop then displays its value and increments by one. An 'if' statement is used to check to see if the variable has a value greater than four, and if it has, a 'break' statement is used to end execution of the loop. Again, the output is the same as the previous examples.
i := 0 for { fmt.Println(i) i++ if i > 4 { break } }
For-each range loop
This type of 'for' loop can iterate over string and more complex variables.
for index, character:= range string { // Statement(s) to execute. }
The below example iterates over a string, displaying the index position and individual characters on a separate line.
for i, j := range "This is a string." { fmt.Println(i, ": ", string(j)) }
This produces the following output. Note that the 'string' function needs to be used to display the character, because, by default the Unicode value is shown.
0 : T 1 : h 2 : i 3 : s 4 : 5 : i 6 : s 7 : 8 : a 9 : 10 : s 11 : t 12 : r 13 : i 14 : n 15 : g 16 : .