go语言的循环
go里的循环比较简单只有for
1.普通for循环
for 初始化语句; 条件语句; 修饰语句 {}
for i := 0; i < 5; i++ {
fmt.Printf("This is the %d iteration\n", i)
}
2.类似while循环
for i >= 0 {
i = i - 1
fmt.Printf("The variable i is now: %d\n", i)
}
3.无限循环
for{
...
}
4.for-range 结构
go特有的,它可以迭代任何一个集合(包括数组和 map)觉得和foreach循环很像
一般形式for ix, val := range coll { }
用来迭代字符串,它能够自动根据 UTF-8 规则识别 Unicode 编码的字符。
for pos, char := range str2 {
fmt.Printf("character %c starts at byte position %d\n", char, pos)
}
输出:
character C starts at byte position 0
character h starts at byte position 1
character i starts at byte position 2
character n starts at byte position 3
character e starts at byte position 4
character s starts at byte position 5
character e starts at byte position 6
character : starts at byte position 7
character starts at byte position 8
character 日 starts at byte position 9
character 本 starts at byte position 12
character 語 starts at byte position 15
break和continue这两个没什么用法好像都一样
标签与 goto(标签命名一般全大写)
package main import "fmt" func main() { LABEL1: for i := 0; i <= 5; i++ { for j := 0; j <= 5; j++ { if j == 4 { continue LABEL1 } fmt.Printf("i is: %d, and j is: %d\n", i, j) } } }
package main func main() { i:=0 HERE: print(i) i++ if i==5 { return } goto HERE }
从接触编程语言开始,就被教导goto结构不能用,代码可读性和程序结构非常不好
the way to go 这本书还没有翻译完呢,才到第六章,得换本资料看了
有疑问加站长微信联系(非本文作者)