[TOC]
如果想要重復執行某些語句,Go 語言中您只有 for 結構可以使用。不要小看它,這個 for 結構比其它語言中的更為靈活。
**注意事項**?其它許多語言中也沒有發現和 do while 完全對等的 for 結構,可能是因為這種需求并不是那么強烈。
## [](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.4.md#541-基于計數器的迭代)5.4.1 基于計數器的迭代
文件 for1.go 中演示了最簡單的基于計數器的迭代,基本形式為:
~~~
for 初始化語句; 條件語句; 修飾語句 {}
~~~
示例 5.6?[for1.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_5/for1.go):
~~~
package main
import "fmt"
func main() {
for i := 0; i < 5; i++ {
fmt.Printf("This is the %d iteration\n", i)
}
}
~~~
輸出:
~~~
This is the 0 iteration
This is the 1 iteration
This is the 2 iteration
This is the 3 iteration
This is the 4 iteration
~~~
由花括號括起來的代碼塊會被重復執行已知次數,該次數是根據計數器(此例為 i)決定的。循環開始前,會執行且僅會執行一次初始化語句?`i := 0;`;這比在循環之前聲明更為簡短。緊接著的是條件語句?`i < 5;`,在每次循環開始前都會進行判斷,一旦判斷結果為 false,則退出循環體。最后一部分為修飾語句?`i++`,一般用于增加或減少計數器。
這三部分組成的循環的頭部,它們之間使用分號?`;`?相隔,但并不需要括號?`()`?將它們括起來。例如:`for (i = 0; i < 10; i++) { }`,這是無效的代碼!
同樣的,左花括號?`{`?必須和 for 語句在同一行,計數器的生命周期在遇到右花括號?`}`?時便終止。一般習慣使用 i、j、z 或 ix 等較短的名稱命名計數器。
特別注意,永遠不要在循環體內修改計數器,這在任何語言中都是非常差的實踐!
您還可以在循環中同時使用多個計數器:
~~~
for i, j := 0, N; i < j; i, j = i+1, j-1 {}
~~~
這得益于 Go 語言具有的平行賦值的特性(可以查看第 7 章 string_reverse.go 中反轉數組的示例)。
您可以將兩個 for 循環嵌套起來:
~~~
for i:=0; i<5; i++ {
for j:=0; j<10; j++ {
println(j)
}
}
~~~
如果您使用 for 循環迭代一個 Unicode 編碼的字符串,會發生什么?
示例 5.7?[for_string.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_5/for_string.go):
~~~
package main
import "fmt"
func main() {
str := "Go is a beautiful language!"
fmt.Printf("The length of str is: %d\n", len(str))
for ix :=0; ix < len(str); ix++ {
fmt.Printf("Character on position %d is: %c \n", ix, str[ix])
}
str2 := "日本語"
fmt.Printf("The length of str2 is: %d\n", len(str2))
for ix :=0; ix < len(str2); ix++ {
fmt.Printf("Character on position %d is: %c \n", ix, str2[ix])
}
}
~~~
輸出:
~~~
The length of str is: 27
Character on position 0 is: G
Character on position 1 is: o
Character on position 2 is:
Character on position 3 is: i
Character on position 4 is: s
Character on position 5 is:
Character on position 6 is: a
Character on position 7 is:
Character on position 8 is: b
Character on position 9 is: e
Character on position 10 is: a
Character on position 11 is: u
Character on position 12 is: t
Character on position 13 is: i
Character on position 14 is: f
Character on position 15 is: u
Character on position 16 is: l
Character on position 17 is:
Character on position 18 is: l
Character on position 19 is: a
Character on position 20 is: n
Character on position 21 is: g
Character on position 22 is: u
Character on position 23 is: a
Character on position 24 is: g
Character on position 25 is: e
Character on position 26 is: !
The length of str2 is: 9
Character on position 0 is: ?
Character on position 1 is: ?
Character on position 2 is: ¥
Character on position 3 is: ?
Character on position 4 is: ?
Character on position 5 is: ?
Character on position 6 is: è
Character on position 7 is: a
Character on position 8 is: ?
~~~
如果我們打印 str 和 str2 的長度,會分別得到 27 和 9。
由此我們可以發現,ASCII 編碼的字符占用 1 個字節,既每個索引都指向不同的字符,而非 ASCII 編碼的字符(占有 2 到 4 個字節)不能單純地使用索引來判斷是否為同一個字符。我們會在第 5.4.4 節解決這個問題。
### [](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.4.md#練習題)練習題
**練習 5.4**?[for_loop.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_5/for_loop.go)
1. 使用 for 結構創建一個簡單的循環。要求循環 15 次然后使用 fmt 包來打印計數器的值。
2. 使用 goto 語句重寫循環,要求不能使用 for 關鍵字。
**練習 5.5**?[for_character.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_5/for_character.go)
創建一個程序,要求能夠打印類似下面的結果(直到每行 25 個字符時為止):
~~~
G
GG
GGG
GGGG
GGGGG
GGGGGG
~~~
1. 使用 2 層嵌套 for 循環。
2. 使用一層 for 循環以及字符串截斷。
**練習 5.6**?[bitwise_complement.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_5/bitwise_complement.go)
使用按位補碼從 0 到 10,使用位表達式?`%b`?來格式化輸出。
**練習 5.7**?Fizz-Buzz 問題:[fizzbuzz.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_5/fizzbuzz.go)
寫一個從 1 打印到 100 的程序,但是每當遇到 3 的倍數時,不打印相應的數字,但打印一次 "Fizz"。遇到 5 的倍數時,打印?`Buzz`?而不是相應的數字。對于同時為 3 和 5 的倍數的數,打印?`FizzBuzz`(提示:使用 switch 語句)。
**練習 5.8**?Fizz-Buzz 問題:[rectangle_stars.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/exercises/chapter_5/rectangle_stars.go)
使用?`*`?符號打印寬為 20,高為 10 的矩形。
## [](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.4.md#542-基于條件判斷的迭代)5.4.2 基于條件判斷的迭代
for 結構的第二種形式是沒有頭部的條件判斷迭代(類似其它語言中的 while 循環),基本形式為:`for 條件語句 {}`。
您也可以認為這是沒有初始化語句和修飾語句的 for 結構,因此?`;;`?便是多余的了。
Listing 5.8?[for2.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_5/for2.go):
~~~
package main
import "fmt"
func main() {
var i int = 5
for i >= 0 {
i = i - 1
fmt.Printf("The variable i is now: %d\n", i)
}
}
~~~
輸出:
~~~
The variable i is now: 4
The variable i is now: 3
The variable i is now: 2
The variable i is now: 1
The variable i is now: 0
The variable i is now: -1
~~~
## [](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.4.md#543-無限循環)5.4.3 無限循環
條件語句是可以被省略的,如?`i:=0; ; i++`?或?`for { }`?或?`for ;; { }`(`;;`?會在使用 gofmt 時被移除):這些循環的本質就是無限循環。最后一個形式也可以被改寫為?`for true { }`,但一般情況下都會直接寫?`for { }`。
如果 for 循環的頭部沒有條件語句,那么就會認為條件永遠為 true,因此循環體內必須有相關的條件判斷以確保會在某個時刻退出循環。
想要直接退出循環體,可以使用 break 語句(第 5.5 節)或 return 語句直接返回(第 6.1 節)。
但這兩者之間有所區別,break 只是退出當前的循環體,而 return 語句提前對函數進行返回,不會執行后續的代碼。
無限循環的經典應用是服務器,用于不斷等待和接受新的請求。
~~~
for t, err = p.Token(); err == nil; t, err = p.Token() {
...
}
~~~
## [](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.4.md#544-for-range-結構)5.4.4 for-range 結構
這是 Go 特有的一種的迭代結構,您會發現它在許多情況下都非常有用。它可以迭代任何一個集合(包括數組和 map,詳見第 7 和 8 章)。語法上很類似其它語言中 foreach 語句,但您依舊可以獲得每次迭代所對應的索引。一般形式為:`for ix, val := range coll { }`。
要注意的是,`val`?始終為集合中對應索引的值拷貝,因此它一般只具有只讀性質,對它所做的任何修改都不會影響到集合中原有的值(**譯者注:如果?`val`?為指針,則會產生指針的拷貝,依舊可以修改集合中的原值**)。一個字符串是 Unicode 編碼的字符(或稱之為?`rune`)集合,因此您也可以用它迭代字符串:
~~~
for pos, char := range str {
...
}
~~~
每個 rune 字符和索引在 for-range 循環中是一一對應的。它能夠自動根據 UTF-8 規則識別 Unicode 編碼的字符。
示例 5.9?[range_string.go](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/examples/chapter_5/range_string.go):
~~~
package main
import "fmt"
func main() {
str := "Go is a beautiful language!"
fmt.Printf("The length of str is: %d\n", len(str))
for pos, char := range str {
fmt.Printf("Character on position %d is: %c \n", pos, char)
}
fmt.Println()
str2 := "Chinese: 日本語"
fmt.Printf("The length of str2 is: %d\n", len(str2))
for pos, char := range str2 {
fmt.Printf("character %c starts at byte position %d\n", char, pos)
}
fmt.Println()
fmt.Println("index int(rune) rune char bytes")
for index, rune := range str2 {
fmt.Printf("%-2d %d %U '%c' % X\n", index, rune, rune, rune, []byte(string(rune)))
}
}
~~~
輸出:
~~~
The length of str is: 27
Character on position 0 is: G
Character on position 1 is: o
Character on position 2 is:
Character on position 3 is: i
Character on position 4 is: s
Character on position 5 is:
Character on position 6 is: a
Character on position 7 is:
Character on position 8 is: b
Character on position 9 is: e
Character on position 10 is: a
Character on position 11 is: u
Character on position 12 is: t
Character on position 13 is: i
Character on position 14 is: f
Character on position 15 is: u
Character on position 16 is: l
Character on position 17 is:
Character on position 18 is: l
Character on position 19 is: a
Character on position 20 is: n
Character on position 21 is: g
Character on position 22 is: u
Character on position 23 is: a
Character on position 24 is: g
Character on position 25 is: e
Character on position 26 is: !
The length of str2 is: 18
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
index int(rune) rune char bytes
0 67 U+0043 'C' 43
1 104 U+0068 'h' 68
2 105 U+0069 'i' 69
3 110 U+006E 'n' 6E
4 101 U+0065 'e' 65
5 115 U+0073 's' 73
6 101 U+0065 'e' 65
7 58 U+003A ':' 3A
8 32 U+0020 ' ' 20
9 26085 U+65E5 '日' E6 97 A5
12 26412 U+672C '本' E6 9C AC
15 35486 U+8A9E '語' E8 AA 9E
~~~
請將輸出結果和 Listing 5.7(for_string.go)進行對比。
我們可以看到,常用英文字符使用 1 個字節表示,而中文字符使用 3 個字符表示。
**練習 5.9**?以下程序的輸出結果是什么?
~~~
for i := 0; i < 5; i++ {
var v int
fmt.Printf("%d ", v)
v = 5
}
~~~
**問題 5.2:**?請描述以下 for 循環的輸出結果:
1.
~~~
for i := 0; ; i++ {
fmt.Println("Value of i is now:", i)
}
~~~
2.
~~~
for i := 0; i < 3; {
fmt.Println("Value of i:", i)
}
~~~
3.
~~~
s := ""
for ; s != "aaaaa"; {
fmt.Println("Value of s:", s)
s = s + "a"
}
~~~
4.
~~~
for i, j, s := 0, 5, "a"; i < 3 && j < 100 && s != "aaaaa"; i, j,
s = i+1, j+1, s + "a" {
fmt.Println("Value of i, j, s:", i, j, s)
}
~~~
- 前言
- 第一部分:學習 Go 語言
- 第1章:Go 語言的起源,發展與普及
- 1.1 起源與發展
- 1.2 語言的主要特性與發展的環境和影響因素
- 第2章:安裝與運行環境
- 2.1 平臺與架構
- 2.2 Go 環境變量
- 2.3 在 Linux 上安裝 Go
- 2.4 在 Mac OS X 上安裝 Go
- 2.5 在 Windows 上安裝 Go
- 2.6 安裝目錄清單
- 2.7 Go 運行時(runtime)
- 2.8 Go 解釋器
- 第3章:編輯器、集成開發環境與其它工具
- 3.1 Go 開發環境的基本要求
- 3.2 編輯器和集成開發環境
- 3.3 調試器
- 3.4 構建并運行 Go 程序
- 3.5 格式化代碼
- 3.6 生成代碼文檔
- 3.7 其它工具
- 3.8 Go 性能說明
- 3.9 與其它語言進行交互
- 第二部分:語言的核心結構與技術
- 第4章:基本結構和基本數據類型
- 4.1 文件名、關鍵字與標識符
- 4.2 Go 程序的基本結構和要素
- 4.3 常量
- 4.4 變量
- 4.5 基本類型和運算符
- 4.6 字符串
- 4.7 strings 和 strconv 包
- 4.8 時間和日期
- 4.9 指針
- 第5章:控制結構
- 5.1 if-else 結構
- 5.2 測試多返回值函數的錯誤
- 5.3 switch 結構
- 5.4 for 結構
- 5.5 Break 與 continue
- 5.6 標簽與 goto
- 第6章:函數(function)
- 6.1 介紹
- 6.2 函數參數與返回值
- 6.3 傳遞變長參數
- 6.4 defer 和追蹤
- 6.5 內置函數
- 6.6 遞歸函數
- 6.7 將函數作為參數
- 6.8 閉包
- 6.9 應用閉包:將函數作為返回值
- 6.10 使用閉包調試
- 6.11 計算函數執行時間
- 6.12 通過內存緩存來提升性能
- 第7章:數組與切片
- 7.1 聲明和初始化
- 7.2 切片
- 7.3 For-range 結構
- 7.4 切片重組(reslice)
- 7.5 切片的復制與追加
- 7.6 字符串、數組和切片的應用
- 第8章:Map
- 8.1 聲明、初始化和 make
- 8.2 測試鍵值對是否存在及刪除元素
- 8.3 for-range 的配套用法
- 8.4 map 類型的切片
- 8.5 map 的排序
- 8.6 將 map 的鍵值對調
- 第9章:包(package)
- 9.1 標準庫概述
- 9.2 regexp 包
- 9.3 鎖和 sync 包
- 9.4 精密計算和 big 包
- 9.5 自定義包和可見性
- 9.6 為自定義包使用 godoc
- 9.7 使用 go install 安裝自定義包
- 9.8 自定義包的目錄結構、go install 和 go test
- 9.9 通過 Git 打包和安裝
- 9.10 Go 的外部包和項目
- 9.11 在 Go 程序中使用外部庫
- 第10章:結構(struct)與方法(method)
- 10.1 結構體定義
- 10.2 使用工廠方法創建結構體實例
- 10.3 使用自定義包中的結構體
- 10.4 帶標簽的結構體
- 10.5 匿名字段和內嵌結構體
- 10.6 方法
- 10.8 垃圾回收和 SetFinalizer
- 第11章:接口(interface)與反射(reflection)
- 11.1 接口是什么
- 11.2 接口嵌套接口
- 11.3 類型斷言:如何檢測和轉換接口變量的類型
- 11.4 類型判斷:type-switch
- 11.5 測試一個值是否實現了某個接口
- 11.6 使用方法集與接口
- 11.7 第一個例子:使用 Sorter 接口排序
- 11.8 第二個例子:讀和寫
- 11.9 空接口
- 11.10 反射包
- 第三部分:Go 高級編程
- 第12章 讀寫數據
- 12.1 讀取用戶的輸入
- 12.2 文件讀寫
- 12.3 文件拷貝
- 12.4 從命令行讀取參數
- 12.5 用buffer讀取文件
- 12.6 用切片讀寫文件
- 12.7 用 defer 關閉文件
- 12.8 使用接口的實際例子:fmt.Fprintf
- 12.9 Json 數據格式
- 12.10 XML 數據格式
- 12.11 用 Gob 傳輸數據
- 12.12 Go 中的密碼學
- 第13章 錯誤處理與測試
- 13.1 錯誤處理
- 13.2 運行時異常和 panic
- 13.3 從 panic 中恢復(Recover)
- 13.4 自定義包中的錯誤處理和 panicking
- 13.5 一種用閉包處理錯誤的模式
- 13.6 啟動外部命令和程序
- 13.7 Go 中的單元測試和基準測試
- 13.8 測試的具體例子
- 13.9 用(測試數據)表驅動測試
- 13.10 性能調試:分析并優化 Go 程序
- 第14章:協程(goroutine)與通道(channel)
- 14.1 并發、并行和協程
- 14.2 使用通道進行協程間通信
- 14.3 協程同步:關閉通道-對阻塞的通道進行測試
- 14.4 使用 select 切換協程
- 14.5 通道,超時和計時器(Ticker)
- 14.6 協程和恢復(recover)
- 第15章:網絡、模版與網頁應用
- 15.1 tcp服務器
- 15.2 一個簡單的web服務器
- 15.3 訪問并讀取頁面數據
- 15.4 寫一個簡單的網頁應用
- 第四部分:實際應用
- 第16章:常見的陷阱與錯誤
- 16.1 誤用短聲明導致變量覆蓋
- 16.2 誤用字符串
- 16.3 發生錯誤時使用defer關閉一個文件
- 16.5 不需要將一個指向切片的指針傳遞給函數
- 16.6 使用指針指向接口類型
- 16.7 使用值類型時誤用指針
- 16.8 誤用協程和通道
- 16.9 閉包和協程的使用
- 16.10 糟糕的錯誤處理
- 第17章:模式
- 17.1 關于逗號ok模式
- 第18章:出于性能考慮的實用代碼片段
- 18.1 字符串
- 18.2 數組和切片
- 18.3 映射
- 18.4 結構體
- 18.5 接口
- 18.6 函數
- 18.7 文件
- 18.8 協程(goroutine)與通道(channel)
- 18.9 網絡和網頁應用
- 18.10 其他
- 18.11 出于性能考慮的最佳實踐和建議
- 附錄