for循环是一种重复控制结构,它允许您有效地编写需要执行特定次数的循环。
Go编程语言中的for循环的语法是:
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
下面是for循环中的控制流程:
如果for子句是( init; condition; increment ),则存在
如果范围(range)可用,则对该范围中的每个项目执行for循环。
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