for
語句是Go
程式設計語言中唯一的迴圈結構。這裡有三種基本型別的for
迴圈。
所有的範例程式碼,都放在
F:\worksp\golang
目錄下。安裝Go程式設計環境請參考:/2/23/798.html
for
迴圈。也可以繼續下一個迴圈的疊代。
for.go
的完整程式碼如下所示 -
// `for` is Go's only looping construct. Here are
// three basic types of `for` loops.
package main
import "fmt"
func main() {
// The most basic type, with a single condition.
i := 1
for i <= 3 {
fmt.Println(i)
i = i + 1
}
// A classic initial/condition/after `for` loop.
for j := 7; j <= 9; j++ {
fmt.Println(j)
}
// `for` without a condition will loop repeatedly
// until you `break` out of the loop or `return` from
// the enclosing function.
for {
fmt.Println("loop")
break
}
// You can also `continue` to the next iteration of
// the loop.
for n := 0; n <= 5; n++ {
if n%2 == 0 {
continue
}
fmt.Println(n)
}
}
執行上面程式碼,將得到以下輸出結果 -
F:\worksp\golang>go run for.go
1
2
3
7
8
9
loop
1
3
5