select就是用來監聽和channel有關的IO操作,當 IO 操作發生時,觸發相應的動作
package main
import (
"fmt"
"time"
)
func main() {
ch := make(chan int)
o := make(chan bool)
go func() {
for {
select {
case <-time.After(3 * time.Second):
fmt.Println("超時")
o <- true
case num := <-ch:
fmt.Println(num)
}
}
}()
<-o
}