我们把接收操作赋值给2个参数,第二个参数就能判断通道是否已经关闭。比如用for循环接收通道中的元素,代码如下:
for {
elem, ok := <-ch1
if !ok {
fmt.Printf("Receiver: close channel\n")
break
}
fmt.Printf("Receiver: received an element:%v\n", elem)
}
在我们开发过程中,有时候为了在方法参数中定义一个通道来收发数据,会定义一个单向通道,如下面代码,第一个通道只能发,第二个通道只能收
var sendChan = make(chan<- int, 1)
var receiveChan1 = make(<- chan int, 1)
还可以定义返回值是单向通道的函数,如下:
func getIntChan() <- chan int{}
func getIntChan1() chan <- int{}
go语言为通道提供了select语句配合使用,类似于java中的switch,也有一个默认的分支,示例如下:
func main() {
// 准备好几个通道。
intChannels := [3]chan int{
make(chan int, 1),
make(chan int, 1),
make(chan int, 1),
}
// 随机选择一个通道,并向它发送元素值。
index := rand.Intn(3)
fmt.Printf("The index: %d\n", index)
intChannels[index] <- index
// 哪一个通道中有可取的元素值,哪个对应的分支就会被执行。
select {
case <-intChannels[0]:
fmt.Println("The first candidate case is selected.")
case <-intChannels[1]:
fmt.Println("The second candidate case is selected.")
case elem := <-intChannels[2]:
fmt.Printf("The third candidate case is selected, the element is %d.\n", elem)
default:
fmt.Println("No candidate case is selected!")
}
}
注意:在for循环中使用select,如果要屏蔽某个case分支,可以将通道赋值为nil
本文来自:51CTO博客
感谢作者:mb5fed72b60246f
查看原文:go语言学习(五):通道的用法
相关阅读 >>
jack liu's Golang personal summary notes
专访Go语言布道师dave cheney:Go语言这十年,只能用“成功”一词总结
更多相关阅读请进入《Go》频道 >>

Go语言101
一个与时俱进的Go编程知识库。