Go by Example: For
for is Go’s only looping construct. Here are three basic types of for loops.
The most basic type, with a single condition.
A classic initial/condition/after for loop.
运行结果
go run for.go
1
2
3
7
8
9
10
for is Go’s only looping construct. Here are three basic types of for loops.
The most basic type, with a single condition.
A classic initial/condition/after for loop.
for without a condition will loop repeatedly until you break out of the loop or return from the enclosing function.
package main import "fmt" func main() { i := 1 for i <= 3 { fmt.Println(i) i = i + 1 } for j := 7; j <= 9; j++ { fmt.Println(j) } for { fmt.Println("loop") break } }
译:
for 关键字是在go语言中唯一一个循环结构,下面的就是for循环的三个基本类型结构
最基本的是一个单条件
一个是 初始值/条件/然后的自身处理条件对于 for循环
for 循环对于没有条件的将会一直循环直到break出循环,或者在外围函数返回
package main import "fmt" func main() { i := 1 for i <= 3 { //相当于while循环 fmt.Println(i) i = i + 1 } for j := 7; j <= 10; j++ { //传统的for循环 fmt.Println(j) } for { //类似于 do。。。while循环 fmt.Println("loop") break } }
运行结果
go run for.go
1
2
3
7
8
9
10
loop
有疑问加站长微信联系(非本文作者)