Go语言中的select语句怎么使用(用法示例解析)

在Go语言中, select语句就像switch语句, 但在select语句中, case语句指的是通信, 即通道上的发送或接收操作。
语法如下:

select{case SendOrReceive1: // Statement case SendOrReceive2: // Statement case SendOrReceive3: // Statement ....... default: // Statement

要点:
Select语句等待, 直到准备开始进行某些通信(发送或接收操作)为止。
例子:
// Go program to illustrate the // concept of select statement package mainimport( "fmt" "time" )// function 1 func portal1(channel1 chan string) {time .Sleep(3* time .Second) channel1 < - "Welcome to channel 1" }// function 2 func portal2(channel2 chan string) {time .Sleep(9* time .Second) channel2 < - "Welcome to channel 2" }// main function func main(){// Creating channels R1:= make(chan string) R2:= make(chan string)// calling function 1 and // function 2 in goroutine go portal1(R1) go portal2(R2)select{// case 1 for portal 1 case op1:= < - R1: fmt.Println(op1)// case 2 for portal 2 case op2:= < - R2: fmt.Println(op2) }}

输出如下:
Welcome to channel 1

说明:在上面的程序中, 门户网站1的睡眠时间为3秒钟, 门户网站2的睡眠时间为9秒钟, 经过它们的睡眠时间后, 他们将准备继续。现在, select语句一直等到他们的睡眠时间, 当门户2唤醒时, 它选择情况2并打印" Welcome to channel 1"。如果门户1在门户2之前醒来, 则输出为"欢迎使用通道2"。
如果select语句不包含任何case语句, 则该select语句将永远等待。
【Go语言中的select语句怎么使用(用法示例解析)】语法如下:
select{}

例子:
// Go program to illustrate the // concept of select statement package main// main function func main() {// Select statement // without any case select{ }}

输出如下:
fatal error: all goroutines are asleep - deadlock!goroutine 1 [select (no cases)]: main.main() /home/runner/main.go:9 +0x20 exit status 2

select语句中的默认语句用于保护select语句不被阻塞。当没有case语句准备进行时, 将执行此语句。
例子:
// Go program to illustrate the // concept of select statement package mainimport "fmt"// main function func main() {// creating channel mychannel:= make(chan int ) select{ case < - mychannel: default :fmt.Println( "Not found" ) } }

输出如下:
Not found

select语句的阻塞意味着当没有case语句准备好并且select语句不包含任何默认语句时, 则select语句将阻塞, 直到至少一个case语句或通信可以继续。
例子:
// Go program to illustrate the // concept of select statement package main// main function func main() {// creating channel mychannel:= make(chan int )// channel is not ready // and no default case select{ case < - mychannel:} }

输出如下:
fatal error: all goroutines are asleep - deadlock!goroutine 1 [chan receive]: main.main() /home/runner/main.go:14 +0x52 exit status 2

在select语句中, 如果准备好处理多种情况, 则可以随机选择其中一种。
例子:
// Go program to illustrate the // concept of select statement package mainimport "fmt"// function 1 func portal1(channel1 chan string){ for i := 0; i < = 3; i++{ channel1 < - "Welcome to channel 1" }}// function 2 func portal2(channel2 chan string){ channel2 < - "Welcome to channel 2" }// main function func main() {// Creating channels R1:= make(chan string) R2:= make(chan string)// calling function 1 and // function 2 in goroutine go portal1(R1) go portal2(R2)// the choice of selection // of case is random select{ case op1:= < - R1: fmt.Println(op1) case op2:= < - R2: fmt.Println(op2) } }

输出如下:
Welcome to channel 2

    推荐阅读