无涯教程-Go - for 循环函数

58 阅读1分钟

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

for - 语法

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

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

for - 示例

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("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

参考链接

www.learnfk.com/go/go-for-l…