gobyexample_range_over_channels

========

参考网站

========

go 遍历管道

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// GoByExample_RangeOverChannels project main.go

// In a [previous](range) example we saw how `for` and
// `range` provide iteration over basic data structures.
// We can also use this syntax to iterate over
// values received from a channel.
// 在遍历的示例中range为基本的数据类型提供了迭代功能。
// 我们同样能用这个语法来迭代从channel接收的值。

package main

import "fmt"

func main() {

// We'll iterate over 2 values in the `queue` channel.
// 我们将从queue这个channel中遍历2个值。
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)

// This `range` iterates over each element as it's
// received from `queue`. Because we `close`d the
// channel above, the iteration terminates after
// receiving the 2 elements. If we didn't `close` it
// we'd block on a 3rd receive in the loop.
// 这个range遍历所有从queue接收的元素。
// 由于我们在前面关闭了channel,
// 迭代器会在接收2个元素后关闭,如果不,
// 循环会被阻塞知道收到第三个元素
//(经过我测试如果没有close的话,运行的时候会报错,
// 程序自己会杀掉main的goroutine)。
for elem := range queue {
fmt.Println(elem)
}
}

// 输出
//one
//two
Fork me on GitHub