In general, looping is the process of repeating the execution of a block of code without stopping as long as the referenced condition is met. You must specify a variable that does iteration over or indicates when the loop will be terminated. In the Go programming language, there is only one looping keyword, namely for. However, its capabilities are a combination of for, foreach, and while in other programming languages.
- Looping by Entering Loop Counter VariablesThe way to do this loop is to enter the loop counter variable and its condition after the For keyword. The general form is almost as same as the C/C++ programming language.General form:
For initialization;condition;iteration {
statement
}
- For loop is similar to the While ConceptThe concept of this loop is to write conditions after the For keyword (only conditions). The declaration and iteration of the counter variable are not written after the keyword, only the looping condition is written. The concept is similar to use While in other programming languages.General form:
For condition {
statement
iteration
}
- Writing the For Keyword without Arguments or ConditionLoops with the For keyword written without conditions, will cause an endless loop (the same as For valuable true). You can stop the loop by using the Break keyword.General form:
For {
statement
iteration
condition
break
}
- Looping using the For and Range Keyword CombinationThis method is used to loop over data of type array where the number of elements has been pre-determined.General form:
Var array = [ ]type{..,..,..}
For var, var := range var_array {
statement
}
- Looping using a Combination of Break and Continue KeywordsBreak keyword is used to forcefully stop an ongoing loop, while Continue is used to force the program to continue to the next loop.General form:
For initialization;condition;iteration {
condition1 {continue}
condition2 {break}
statement
}
- Nested LoopThe way of implementing nested loops in Go programming is more or less the same as nested loops in other programming languages, namely by writing a block of looping statements inside the loop.General form:
For initialization;condition;iteration {
For initialization;condition;iteration
{statement}
statement
}
- Looping by Utilise Labeling TechniquesIn the case of nested loops, break and continue apply to the loop block where break and continue are used. There is a way for these two keywords to target the outermost loop or certain loops, namely by using a labeling technique.General form:
label_name:
For initialization;condition;iteration {
For initialization;condition;iteration {
condition {
break label_name
}
statement
}
}