for
语句是Go
编程语言中唯一的循环结构。这里有三种基本类型的for
循环。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:/tutorial/detail-5562.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 7 loop