Loops
In real-world applications, you’re often going to need to run the same logic repeatedly. It’s common to have to deal with multiple inputs and give multiple outputs. Loops are the simplest way of repeating your logic.
Go only has one looping statement, for
, but it’s a flexible one. There are two distinct forms: the first is used a lot for ordered collections such as arrays and slices, which we’ll cover more later. The sort of loop used for ordered collections looks as follows:
for <initial statement>; <condition>; <post statement> { <statements> }
The initial
statement is just like the one found in if
and switch
statements. An initial
statement runs before everything else and allows the same simple statements that we defined before. The condition is checked before each loop to see whether the statements should be run or whether the loop should stop. As with an initial
statement, condition
also allows simple...