Go / 系统课时
用 for 与 range 写循环
用 for 与 range 写循环
Go 只有一种循环关键字 for,但它同时覆盖计数循环、条件循环和无限循环;遍历数组、切片、字符串等集合时再配合 range。本篇通过可运行示例掌握三种循环形态,以及索引、元素值和空标识符的处理方式。
学习目标
- 使用
for编写计数循环、条件循环和可控的无限循环。 - 使用
range遍历切片,并正确接收索引和值。 - 使用
_忽略不需要的返回值,避免产生未使用变量错误。
用 for 覆盖三种循环形态
最常见的计数循环由初始化语句、条件和后置语句组成,三部分之间使用分号。Go 不使用 while 关键字,把初始化和后置语句去掉后,for condition 就承担同样职责。
package main
import "fmt"
func main() {
for i := 0; i < 3; i++ {
fmt.Println("count", i)
}
n := 3
for n > 0 {
fmt.Println("left", n)
n--
}
}预期输出:
count 0
count 1
count 2
left 3
left 2
left 1计数循环中的 i 从 0 开始,在 i == 3 时条件失败,因此一共执行 3 次。条件循环则每轮修改 n,否则条件始终为真就会形成死循环。
控制无限循环的退出位置
省略条件后写成 for {} 就是无限循环,常用于服务轮询、队列消费或“直到满足条件才退出”的处理过程。必须明确安排 break、return 或其他退出路径。
package main
import "fmt"
func main() {
attempt := 0
for {
attempt++
fmt.Println("attempt", attempt)
if attempt == 3 {
break
}
}
}预期输出:
attempt 1
attempt 2
attempt 3break 只结束它所在的最内层 for、switch 或 select。若循环体没有任何可达的退出条件,这段程序会一直运行,因此编写无限循环时应把退出条件放在容易检查的位置。
用 range 同时取得索引和值
遍历切片时,range 每轮可以产生两个值:第一个是索引,第二个是该位置的元素值。下面统计价格总和,并把索引一起打印出来。
package main
import "fmt"
func main() {
prices := []int{12, 18, 25}
total := 0
for index, price := range prices {
fmt.Printf("index=%d price=%d\n", index, price)
total += price
}
fmt.Println("total", total)
}预期输出:
index=0 price=12
index=1 price=18
index=2 price=25
total 55这里的索引依次为 0、1、2。对切片而言,第二个变量 price 接收当前元素的值;如果只想访问元素而不需要索引,就不应该额外保留一个无用变量。
用空标识符忽略不需要的值
Go 不允许声明局部变量后完全不使用,因此只需要 range 的第二个值时,要用空标识符 _ 丢弃索引。如果只需要索引,则可以只写一个变量。
package main
import "fmt"
func main() {
names := []string{"Ada", "Linus", "Ken"}
for _, name := range names {
fmt.Println(name)
}
for index := range names {
fmt.Println("index", index)
}
}预期输出:
Ada
Linus
Ken
index 0
index 1
index 2写成 for index, name := range names 却只使用 name 会因为 index 未使用而无法编译;正确做法是改为 for _, name := range names。反过来,只要索引时直接写 for index := range names 即可,不需要再补一个 _。
在 continue 与 break 之间做选择
continue 跳过当前这一轮剩余语句,继续下一轮;break 则直接结束循环。下面只累加 1 到 10 中的奇数,并在结果首次超过 15 后停止。
package main
import "fmt"
func main() {
total := 0
for n := 1; n <= 10; n++ {
if n%2 == 0 {
continue
}
total += n
if total > 15 {
break
}
}
fmt.Println(total)
}预期输出:
25累计过程依次是 1、4、9、16、25;当加入 9 后总和为 25,并满足 total > 15,因此循环结束。需要“跳过某些元素”时用 continue,需要“后续元素都不再处理”时用 break。