GO 入门指南
  • README
  • 开始
    • 前言
  • 第一部分:学习 Go 语言
    • 第1章:Go 语言的起源,发展与普及
      • 起源与发展
      • 语言的主要特性与发展的环境和影响因素
    • 第2章:安装与运行环境
      • 平台与架构
      • Go 环境变量
      • 在 Linux 上安装 Go
      • 在 Mac OS X 上安装 Go
      • 在 Windows 上安装 Go
      • 安装目录清单
      • Go 运行时(runtime)
      • Go 解释器
    • 第3章: 编辑器、集成开发环境与其它工具
      • Go 开发环境的基本要求
      • 编辑器和集成开发环境
      • 调试器
      • 构建并运行 Go 程序
      • 格式化代码
      • 生成代码文档
      • 其它工具
      • Go 性能说明
      • 与其它语言进行交互
  • 第二部分:语言的核心结构与技术
    • 第4章:基本结构和基本数据类型
      • 文件名、关键字与标识符
      • Go 程序的基本结构和要素
      • 常量
      • 变量
      • 基本类型和运算符
      • 字符串
      • strings 和 strconv 包
      • 时间和日期
      • 指针
    • 第5章:控制结构
      • if-else 结构
      • 测试多返回值函数的错误
      • switch 结构
      • for 结构
      • Break 与 continue
      • 标签与 goto
    • 第6章:函数(function)
      • 介绍
      • 函数参数与返回值
      • 传递变长参数
      • defer 和追踪
      • 内置函数
      • 递归函数
      • 将函数作为参数
      • 闭包
      • 应用闭包:将函数作为返回值
      • 使用闭包调试
      • 计算函数执行时间
      • 通过内存缓存来提升性能
    • 第7章:数组与切片
      • 声明和初始化
      • 切片
      • For-range 结构
      • 切片重组(reslice)
      • 切片的复制与追加
      • 字符串、数组和切片的应用
    • 第8章:Map
      • 声明、初始化和 make
      • 测试键值对是否存在及删除元素
      • for-range 的配套用法
      • map 类型的切片
      • map 的排序
      • 将 map 的键值对调
    • 第9章:包(package)
      • 标准库概述
      • regexp 包
      • 锁和 sync 包
      • 精密计算和 big 包
      • 自定义包和可见性
      • 为自定义包使用 godoc
      • 使用 go install 安装自定义包
      • 自定义包的目录结构、go install 和 go test
      • 通过 Git 打包和安装
      • Go 的外部包和项目
      • 在 Go 程序中使用外部库
    • 第10章:结构(struct)与方法(method)
      • 结构体定义
      • 使用工厂方法创建结构体实例
      • 使用自定义包中的结构体
      • 带标签的结构体
      • 匿名字段和内嵌结构体
      • 方法
      • 类型的 String() 方法和格式化描述符
      • 垃圾回收和 SetFinalizer
    • 第11章:接口(interface)与反射(reflection)
      • 接口是什么
      • 接口嵌套接口
      • 类型断言:如何检测和转换接口变量的类型
      • 类型判断:type-switch
      • 测试一个值是否实现了某个接口
      • 使用方法集与接口
      • 第一个例子:使用 Sorter 接口排序
      • 第二个例子:读和写
      • 空接口
      • 反射包
      • Printf 和反射
      • 接口与动态类型
      • 总结:Go 中的面向对象
      • 结构体、集合和高阶函数
  • 第三部分:Go 高级编程
    • 第12章:读写数据
      • 读取用户的输入
      • 文件读写
      • 文件拷贝
      • 从命令行读取参数
      • 用 buffer 读取文件
      • 用切片读写文件
      • 用 defer 关闭文件
      • 使用接口的实际例子:fmt.Fprintf
      • JSON 数据格式
      • XML 数据格式
      • 用 Gob 传输数据
      • Go 中的密码学
    • 第13章:错误处理与测试
      • 错误处理
      • 运行时异常和 panic
      • 从 panic 中恢复(Recover)
      • 自定义包中的错误处理和 panicking
      • 一种用闭包处理错误的模式
      • 启动外部命令和程序
      • Go 中的单元测试和基准测试
      • 测试的具体例子
      • 用(测试数据)表驱动测试
      • 性能调试:分析并优化 Go 程序
    • 第14章:协程(goroutine)与通道(channel)
      • 并发、并行和协程
      • 协程间的信道
      • 协程的同步:关闭通道-测试阻塞的通道
      • 使用 select 切换协程
      • 通道、超时和计时器(Ticker)
      • 协程和恢复(recover)
      • 新旧模型对比:任务和worker
      • 惰性生成器的实现
      • 实现 Futures 模式
      • 复用
      • 限制同时处理的请求数
      • 链式协程
      • 在多核心上并行计算
      • 并行化大量数据的计算
      • 漏桶算法
      • 对Go协程进行基准测试
      • 使用通道并发访问对象
    • 第15章:网络、模版与网页应用
      • tcp 服务器
      • 一个简单的 web 服务器
      • 访问并读取页面数据
      • 写一个简单的网页应用
      • 确保网页应用健壮
      • 用模板编写网页应用
      • 探索 template 包
      • 精巧的多功能网页服务器
      • 用 rpc 实现远程过程调用
      • 基于网络的通道 netchan
      • 与 websocket 通信
      • 用 smtp 发送邮件
  • 第四部分:实际应用
    • 第16章:常见的陷阱与错误
      • 误用短声明导致变量覆盖
      • 误用字符串
      • 发生错误时使用 defer 关闭一个文件
      • 何时使用new()和make()
      • 不需要将一个指向切片的指针传递给函数
      • 使用指针指向接口类型
      • 使用值类型时误用指针
      • 误用协程和通道
      • 闭包和协程的使用
      • 糟糕的错误处理
    • 第17章:模式
      • 逗号 ok 模式
      • defer 模式
      • 可见性模式
      • 运算符模式和接口
    • 第18章:出于性能考虑的实用代码片段
      • 字符串
      • 数组和切片
      • 映射
      • 结构体
      • 接口
      • 函数
      • 文件
      • 协程(goroutine)与通道(channel)
      • 网络和网页应用
      • 其他
      • 出于性能考虑的最佳实践和建议
    • 第19章:构建一个完整的应用程序
      • 简介
      • 短网址项目简介
      • 数据结构
      • 用户界面:web 服务端
      • 持久化存储:gob
      • 用协程优化性能
      • 以 json 格式存储
      • 多服务器处理架构
      • 使用代理缓存
      • 总结和增强
    • 第 20 章:Go 语言在 Google App Engine 的使用
      • 什么是 Google App Engine?
      • 云上的 Go
      • 安装 Go App Engine SDK:为 Go 部署的开发环境
      • 建造你自己的 Hello world 应用
      • 使用用户服务和探索其 API
      • 处理窗口
      • 使用数据存储
      • 上传到云端
    • 第 21 章:真实世界中 Go 的使用
      • Heroku:一个使用 Go 的高度可用一致数据存储
      • MROffice:一个使用 Go 的呼叫中心网络电话 (eBook/VOIP) 系统
      • Atlassian:一个虚拟机群管理系统
      • Camilistore:一个可寻址内容存储系统
      • Go 语言的其他应用
  • 附录
    • 其他
      • 关于本文16.10.2小结糟糕错误处理的一些见解
    • A 代码引用
    • B 有趣的 Go 引用
    • C 代码示例列表
      • 目录
      • 第2章示例
      • 第3章示例
      • 第4章示例
      • 第5章示例
      • 第6章示例
      • 第7章示例
      • 第8章示例
      • 第9章示例
      • 第10章示例
      • 第11章示例
      • 第12章示例
      • 第13章示例
      • 第14章示例
      • 第15章示例
      • 第16章示例
      • 第19章示例
      • 第20章示例
    • D 书中的包引用
    • E 书中的工具引用
    • F 常见问题解答
    • G 习题答案
      • 第4章答案
      • 第5章答案
      • 第6章答案
      • 第7章答案
      • 第8章答案
      • 第9章答案
      • 第10章答案
      • 第11章答案
      • 第12章答案
      • 第13章答案
      • 第14章答案
      • 第15章答案
      • 第16章答案
      • 第19章答案
      • 第20章答案
    • H 参考文献
Powered by GitBook
On this page
  • 5.4.1 基于计数器的迭代
  • 练习题
  • 5.4.2 基于条件判断的迭代
  • 5.4.3 无限循环
  • 5.4.4 for-range 结构
  • 链接

Was this helpful?

  1. 第二部分:语言的核心结构与技术
  2. 第5章:控制结构

for 结构

Previousswitch 结构NextBreak 与 continue

Last updated 2 years ago

Was this helpful?

如果想要重复执行某些语句,Go 语言中您只有 for 结构可以使用。不要小看它,这个 for 结构比其它语言中的更为灵活。

注意事项 其它许多语言中也没有发现和 do-while 完全对等的 for 结构,可能是因为这种需求并不是那么强烈。

5.4.1 基于计数器的迭代

文件 for1.go 中演示了最简单的基于计数器的迭代,基本形式为:

for 初始化语句; 条件语句; 修饰语句 {}

示例 5.6 :

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 {}

您可以将两个 for 循环嵌套起来:

for i:=0; i<5; i++ {
	for j:=0; j<10; j++ {
		println(j)
	}
}

如果您使用 for 循环迭代一个 Unicode 编码的字符串,会发生什么?

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: ª 
Character on position 8 is: ž 

如果我们打印 str 和 str2 的长度,会分别得到 27 和 9。

练习题

  1. 使用 for 结构创建一个简单的循环。要求循环 15 次然后使用 fmt 包来打印计数器的值。

  2. 使用 goto 语句重写循环,要求不能使用 for 关键字。

创建一个程序,要求能够打印类似下面的结果(尾行达 25 个字符为止):

G
GG
GGG
GGGG
GGGGG
GGGGGG
  1. 使用 2 层嵌套 for 循环。

  2. 仅用 1 层 for 循环以及字符串连接。

使用按位补码从 0 到 10,使用位表达式 %b 来格式化输出。

写一个从 1 打印到 100 的程序,但是每当遇到 3 的倍数时,不打印相应的数字,但打印一次 "Fizz"。遇到 5 的倍数时,打印 Buzz 而不是相应的数字。对于同时为 3 和 5 的倍数的数,打印 FizzBuzz(提示:使用 switch 语句)。

使用 * 符号打印宽为 20,高为 10 的矩形。

5.4.2 基于条件判断的迭代

for 结构的第二种形式是没有头部的条件判断迭代(类似其它语言中的 while 循环),基本形式为:for 条件语句 {}。

您也可以认为这是没有初始化语句和修饰语句的 for 结构,因此 ;; 便是多余的了。

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

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() {
	...
}

5.4.4 for-range 结构

要注意的是,val 始终为集合中对应索引的值拷贝,因此它一般只具有只读性质,对它所做的任何修改都不会影响到集合中原有的值(译者注:如果 val 为指针,则会产生指针的拷贝,依旧可以修改集合中的原值)。一个字符串是 Unicode 编码的字符(或称之为 rune)集合,因此您也可以用它迭代字符串:

for pos, char := range str {
...
}

每个 rune 字符和索引在 for-range 循环中是一一对应的。它能够自动根据 UTF-8 规则识别 Unicode 编码的字符。

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

我们可以看到,常用英文字符使用 1 个字节表示,而汉字(译者注:严格来说,“Chinese: 日本語”的 Chinese 应该是 Japanese)使用 3 个字符表示。

练习 5.9 以下程序的输出结果是什么?

for i := 0; i < 5; i++ {
	var v int
	fmt.Printf("%d ", v)
	v = 5
}

问题 5.2: 请描述以下 for 循环的输出结果:

for i := 0; ; i++ {
	fmt.Println("Value of i is now:", i)
}
for i := 0; i < 3; {
	fmt.Println("Value of i:", i)
}
s := ""
for ; s != "aaaaa"; {
	fmt.Println("Value of s:", s)
	s = s + "a"
}
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 语言具有的平行赋值的特性(可以查看 中反转数组的示例)。

示例 5.7 :

由此我们可以发现,ASCII 编码的字符占用 1 个字节,既每个索引都指向不同的字符,而非 ASCII 编码的字符(占有 2 到 4 个字节)不能单纯地使用索引来判断是否为同一个字符。我们会在 解决这个问题。

练习 5.4

练习 5.5

练习 5.6

练习 5.7 Fizz-Buzz 问题:

练习 5.8

Listing 5.8 :

这是 Go 特有的一种的迭代结构,您会发现它在许多情况下都非常有用。它可以迭代任何一个集合(包括数组和 map,详见第 和 章)。语法上很类似其它语言中的 foreach 语句,但您依旧可以获得每次迭代所对应的索引。一般形式为:for ix, val := range coll { }。

示例 5.9 :

请将输出结果和 Listing 5.7()进行对比。

上一节:

下一节:

for1.go
第 7 章
string_reverse.go
for_string.go
第 5.4.4 节
for_loop.go
for_character.go
bitwise_complement.go
fizzbuzz.go
rectangle_stars.go
for2.go
7
8
range_string.go
for_string.go
目录
switch 结构
Break 与 continue