Golang的for和C語言有八成像。範例:
for i := 0; i <= 100; i++ {
// do something
}
巢狀迴圈:
for i := 0; i <= 100; i++ {
for j := 0; j <= 100; j++ {
do something
}
}
或是類似while用法的for迴圈:
i := 0
for i <= 10 {
do something
}
break就是終止迴圈執行
無條件無窮for迴圈,當然最後最好有個終止條件break:
i := 0
for {
do something
if i >= 100 {
break;
}
i++
}
有break當然也會有continue,continue就是略過本次的迴圈,直接進行下一輪:
for {
i++
if i%2 == 0 {
continue
}
fmt.Print(i)
if i > 50 {
break
}