golang跳出for循环——匿名函数

栏目: Go · 发布时间: 7年前

内容简介:搜索了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循环——匿名函数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms on Strings, Trees and Sequences

Algorithms on Strings, Trees and Sequences

Dan Gusfield / Cambridge University Press / 1997-5-28 / USD 99.99

String algorithms are a traditional area of study in computer science. In recent years their importance has grown dramatically with the huge increase of electronically stored text and of molecular seq......一起来看看 《Algorithms on Strings, Trees and Sequences》 这本书的介绍吧!

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具