目录

for循环

for循环是重复控制结构。 它允许您编写需要执行特定次数的循环。

语法 (Syntax)

Go编程语言中for循环的语法是 -

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

for循环中的控制流程如下 -

  • 如果condition可用,则只要条件为真,就执行for循环。

  • 如果存在( init; condition; increment )for子句则 -

    • init步骤首先执行,只执行一次。 此步骤允许您声明和初始化任何循环控制变量。 只要出现分号,就不需要在此处输入声明。

    • 接下来,评估condition 。 如果为真,则执行循环体。 如果为false,则循环体不执行,控制流在for循环之后跳转到下一个语句。

    • 在执行for循环体后,控制流会跳回到increment语句。 此语句允许您更新任何循环控制变量。 只要在条件之后出现分号,此语句就可以留空。

    • 现在再次评估该条件。 如果为真,则循环执行并且过程自身重复(循环体,然后是增量步,然后是条件)。 条件变为false后,for循环终止。

  • 如果range可用,则对该范围中的每个项执行for循环。

流程图 (Flow Diagram)

Go中的for循环

例子 (Example)

package main
import "fmt"
func main() {
   var b int = 15
   var a int
   numbers := [6]int{1, 2, 3, 5} 
   /* for loop execution */
   for a := 0; a < 10; a++ {
      fmt.Printf("value of a: %d\n", a)
   }
   for a < b {
      a++
      fmt.Printf("value of a: %d\n", a)
   }
   for i,x:= range numbers {
      fmt.Printf("value of x = %d at %d\n", x,i)
   }   
}

编译并执行上述代码时,会产生以下结果 -

value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of x = 1 at 0
value of x = 2 at 1
value of x = 3 at 2
value of x = 5 at 3
value of x = 0 at 4
value of x = 0 at 5
↑回到顶部↑
WIKI教程 @2018