1. channel的select语句
在Go语言,select只能和channel一起使用。
select语句的分支有两种,一种为case分支,另一种为default分支。
2. select专为操作channel而存在的。每一个case表达式,只能包含操作channel的表达式
package mainimport ("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讲
https://github.com/hyper0x/Golang_Puzzlers