内容简介:搜索了golang退出for循环的方法,基本都是围绕 break label 和 goto。我觉得这两种方式都存在在程序里乱跳的缺点。想到了一个用匿名函数的方式,记录一下
搜索了golang退出for循环的方法,基本都是围绕 break label 和 goto。我觉得这两种方式都存在在程序里乱跳的缺点。想到了一个用匿名函数的方式,记录一下
匿名函数方式退出for循环
- 直接上代码
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
}
以上所述就是小编给大家介绍的《golang跳出for循环——匿名函数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Mastering Flask
Jack Stouffer / Packt Publishing / 2015-9-30 / USD 49.99
Work with scalable Flask application structures to create complex web apps Discover the most powerful Flask extensions and learn how to create one Deploy your application to real-world platforms......一起来看看 《Mastering Flask》 这本书的介绍吧!