1. channel的select语句
在Go语言,select只能和channel一起使用。
select语句的分支有两种,一种为case分支,另一种为default分支。
2. select专为操作channel而存在的。每一个case表达式,只能包含操作channel的表达式
package main
import (
"fmt"
"math/rand"
)
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, ok := <-intChannels[2]:
//检查通道是否关闭
if ok {
fmt.Printf("The third candidate case is selected, the element is %d.\n", elem)
}
default:
fmt.Println("No candidate case is selected!")
}
}
https://play.golang.org/p/UfzHq28E5Rm
3. select 语句,要注意的事情
a. 如果没有default分支,一旦所有的case表达式,都没有满足条件,就会阻塞在select语句,直到至少有一个case表达式满足条件为止。
b. 有加入default分支,在没有满足case表达式时,会选择default分支,select语句不会被阻塞。
c. 确认channel是否被关闭。 (如上面的范例)
d. select语句只能对其中的每一个case表达式各求值一次。(如需执行多次,需要通过for语句)
参考来源:
郝林-Go语言核心36讲
正文 如果还没有看Day28的话,建议可以先回去看,不然接下来可能搞不清楚状况。 延续昨天的内容,我...
前言 本文说明如何进行下单作业。 程序实作 # 设定交易标的 # 以台股上市股票:长荣 contra...
在上一篇我们看到,即便我们能不写程序就设定一些自动回覆,仍然相当麻烦,如果需要的功能更多,更无法应付...
在此之前,我们已经介绍过BERT的核心概念迁移学习Transfer Learning以及它的输入输出...
缘由 很多时候我们会使用docker作为环境的控管,确保服务执行时环境是一致的。 但某些时候我们可能...