for
迴圈是一種重複控制結構,它允許您有效地編寫需要執行特定次數的迴圈。
Go程式設計語言中的for
迴圈的語法是:
for [condition | ( init; condition; increment ) | Range]
{
statement(s);
}
下面是for
迴圈中的控制流程:
for
迴圈就執行。如果for
子句是( init; condition; increment ),則存在
false
,迴圈的主體不執行,控制流跳到for
迴圈之後的下一個語句。for
迴圈的主體執行後,控制流跳回到increment語句。此語句允許更新任何迴圈控制變數。 此語句可以留空,只要有一個分號出現。for
迴圈終止。如果範圍(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