Latest web development tutorials

Go language for loop

Go Language loop Go Language loop

for loop is a loop control structure, you can perform the specified number of cycles.

grammar

Go Language For loop has 3 forms, only one of them with a semicolon.

And C language for the same:

for init; condition; post { }

And C while the same:

for condition { }

And C is for (;;) as:

for { }
  • init: general assignment expression, the control variable initial value;
  • condition: logical expression or relational expression, the loop control condition;
  • post: general assignment expression, increment or decrement the control variable.

Process for statement is executed as follows:

  • ① first initial value of expression 1;
  • ② determine assignment expression init meets the given conditions, if it is true, the loop condition, the loop body statement is executed, and then perform the post, into the second loop, then determining condition; otherwise, judging condition is false, condition is not satisfied, the termination for loop, the loop body statement.

range format for loop can slice, map, arrays, strings, etc. iteration loop. Format is as follows:

for key, value := range oldMap {
    newMap[key] = value
}

for flow statement syntax as shown below:

Examples

package main

import "fmt"

func main() {

   var b int = 15
   var a int

   numbers := [6]int{1, 2, 3, 5} 

   /* for 循环 */
   for a := 0; a < 10; a++ {
      fmt.Printf("a 的值为: %d\n", a)
   }

   for a < b {
      a++
      fmt.Printf("a 的值为: %d\n", a)
      }

   for i,x:= range numbers {
      fmt.Printf("第 %d 位 x 的值 = %d\n", i,x)
   }   
}

Run the above example output is:

a 的值为: 0
a 的值为: 1
a 的值为: 2
a 的值为: 3
a 的值为: 4
a 的值为: 5
a 的值为: 6
a 的值为: 7
a 的值为: 8
a 的值为: 9
a 的值为: 1
a 的值为: 2
a 的值为: 3
a 的值为: 4
a 的值为: 5
a 的值为: 6
a 的值为: 7
a 的值为: 8
a 的值为: 9
a 的值为: 10
a 的值为: 11
a 的值为: 12
a 的值为: 13
a 的值为: 14
a 的值为: 15
第 0 位 x 的值 = 1
第 1 位 x 的值 = 2
第 2 位 x 的值 = 3
第 3 位 x 的值 = 5
第 4 位 x 的值 = 0
第 5 位 x 的值 = 0

Go Language loop Go Language loop