Go by Example: Range over Channels通道上的range操作

英文源地址
在上一篇的示例中, 我们看到了for和range操作如何提供对数据结构的迭代.我们还可以使用该语法从通道接收的值.

package main

import "fmt"

func main() {
    
    
	// 我们将遍历queue通道中过的两个值
	queue := make(chan string, 2)
	queue <- "one"
	queue <- "two"
	close(queue)

	// 当从queue中接收到每个元素后, range将遍历每个elem.
	// 因为我们关闭了上面的通道, 所以在接收到2个元素后终止运行
	for elem := range queue {
    
    
		fmt.Println(elem)
	}
}
$ go run range-over-channels.go
one
two

此实例还展示了关闭非空通道但仍然可以接收剩余值的可能性.
下一节将介绍: Timers定时器

猜你喜欢

转载自blog.csdn.net/weixin_43547795/article/details/130871033
今日推荐