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