Go programming example [Channel traversal Channels Range]

Reading table of contents

In the previous example, we said that for and range provide iteration functions for basic data structures.

We can also use this syntax to iterate over values ​​obtained from a channel.

// range-over-channels.go
package main

import "fmt"

func main() {
    
    

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

	// 这个 `range` 迭代从 `queue` 中得到的每个值。因为我们
	// 在前面 `close` 了这个通道,这个迭代会在接收完 2 个值
	// 之后结束。如果我们没有 `close` 它,我们将在这个循环中
	// 继续阻塞执行,等待接收第三个值
	for elem := range queue {
    
    
		fmt.Println(elem)
	}
}
[root@bogon test]# go run range-over-channels.go
one
two
[root@bogon test]# 

This example also allows us to see that a non-empty channel can also be closed, but the remaining values ​​in the channel can still be received.

Guess you like

Origin blog.csdn.net/weiguang102/article/details/129746870