Go: Loops

for Loop

It executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.

for [condition |  ( init; condition; increment ) | Range] {
   statement(s);
}

Nested for Loops

These are one or multiple loops inside any for loop.

for [condition |  ( init; condition; increment ) | Range] {
   for [condition |  ( init; condition; increment ) | Range] {
      statement(s);
   }
   statement(s);
}

Simple range in for loop

for i, j:= range rvariable{
   // statement..
}

Using for loop for strings

A for loop can iterate over the Unicode code point for a string.

for index, chr:= range str{
     // Statement..
}

For Maps

A for loop can iterate over the key and value pairs of the map.

for key, value := range map { 
     // Statement.. 
}

For Channel

A for loop can iterate over the sequential values sent on the channel until it closed.

for item := range Chnl { 
     // statements..
}

break statement

It terminates a for loop or switch statement and transfers execution to the statement immediately following the for loop or switch.

break;

continue statement

It causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

continue;

goto statement

It transfers control to the labeled statement.

goto label;
..
.
label: statement;

Leave a Reply

Your email address will not be published. Required fields are marked *