// 只能从返回通道接收数据funcgetIntChan()<-chanint{
num :=5
ch :=make(chanint, num)for i :=0; i < num; i++{
ch <- i
}close(ch)return ch
}
intChan2 :=getIntChan()// 不断从channel中取值,即便关闭了也会取干净。// 没有元素了会阻塞。不过这里getIntChan已经关闭了通道,所以取出所有元素后会结束。// 如果返回的intChan2是nil,则for语句会阻塞。for elem :=range intChan2 {
fmt.Printf("The element in intChan2: %v\n", elem)}
Select语句
基本用法
// 准备好几个通道。
intChannels :=[3]chanint{make(chanint,1),make(chanint,1),make(chanint,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!")}
intChan :=make(chanint,1)// 一秒后关闭通道。
time.AfterFunc(time.Second,func(){close(intChan)})select{case_, ok :=<-intChan:if!ok {
fmt.Println("The candidate case is closed.")break}
fmt.Println("The candidate case is selected.")}
分支选择规则
求值顺序从上到下,选择规则伪随机。
var channels =[3]chanint{nil,make(chanint),nil,}var numbers =[]int{1,2,3}funcmain(){select{casegetChan(0)<-getNumber(0):
fmt.Println("The first candidate case is selected.")casegetChan(1)<-getNumber(1):
fmt.Println("The second candidate case is selected.")casegetChan(2)<-getNumber(2):
fmt.Println("The third candidate case is selected")default:
fmt.Println("No candidate case is selected!")}}funcgetNumber(i int)int{
fmt.Printf("numbers[%d]\n", i)return numbers[i]}funcgetChan(i int)chanint{
fmt.Printf("channels[%d]\n", i)return channels[i]}
channels[0]
numbers[0]
channels[1]
numbers[1]
channels[2]
numbers[2]
No candidate case is selected!