Go for and for range

for

Go for is a loop control structure that allows executing a block of code a specified number of times. It comes in three main forms:

for init; condition; post {
    //...
}
//the common for loop
for i := 0; i < n; i++ {
   fmt.Println(i)
}

##########################################
for condition {
    //...
}
//similar to while (n > 0) and for (; n > 0;) 
for n > 0 {                
   fmt.Println(n)
   n-- 
}

##########################################
for {
    //...
}
//similar to while (true) and for (;;)
for {
   fmt.Println("*")
}

for range

For range acts like an iterator, iterating over elements of a slice, array, string, map, or channel. It returns either (index: value) pairs for slices, arrays, and strings, or (key: value) pairs for maps. For channels, it iterates over the values sent on the channel.

//variable can be string、array/slice、map、channel
for key, value := range variable {
   //...
}

Differences between For and For Range

For range can do everything that a regular for loop can do, but it also allows traversing maps with string keys and channels, which a regular for loop cannot do directly.

break、continue、goto

These loop statements compared to other languages:

  1. break: To exit the current for or for range loop
  2. continue: To skip the rest of the current iteration and proceed to the next iteration
  3. goto: Unconditional jumps to labeled statements are possible but generally discouraged in Go due to their potential to make code harder to understand and maintain.

 

Take a break

👉👉👉 【Jade Dynasty EP49】Gui Li and Xiao Bai went to the Qilidong and competed with the locals in drinking