搜索了golang退出for循環的方法,基本都是圍繞 break label 和 goto。我以爲這兩種方式都存在在程序裏亂跳的缺點。想到了一個用匿名函數的方式,記錄一下golang
func main(){ begin := time.Now() ch := make(chan int,4) for i := 1; i < 5; i++ { go worker(ch,i) } time.Sleep(time.Millisecond ) func() { for{ select { case temp:=<-ch: fmt.Println("Read channel : ",temp) default: return } } }() close(ch) duration := time.Since(begin) fmt.Println("Duration: ",duration) time.Sleep(time.Second) } func worker(ch chan int,id int){ fmt.Println("ID:",id,"is sending channel") ch <- id }