for語(yǔ)句是Go編程語(yǔ)言中唯一的循環(huán)結(jié)構(gòu)。這里有三種基本類型的for循環(huán)。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.com/go/go_environment.html
for循環(huán)。也可以繼續(xù)下一個(gè)循環(huán)的迭代。
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)
}
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run for.go
1
2
3
7
8
9
loop
1
3
5