标签:
我们在for多层嵌套时,有时候需要直接跳出所有嵌套循环, 这时候就可以用到go的label breaks特征了。
先看一个范例代码:
package main
import (   
    "fmt"    
) 
func main() {   
    fmt.Println("1") 
Exit:   
    for i := 0; i < 9; i++ {    
        for j := 0; j < 9; j++ {    
            if i+j > 15 {    
                fmt.Print("exit")    
                break Exit    
            }    
        }    
    } 
    fmt.Println("3")   
}
执行效果:
注意,
break的标签和goto的标签的区别可以参考下面代码:
JLoop:   
    for i := 0; i < 10; i++ {    
        fmt.Println("label i is ", i)    
        for j := 0; j < 10; j++ {    
            if j > 5 {    
                //跳到外面去啦,但是不会再进来这个for循环了    
                break JLoop    
            }    
        }    
    } 
    //跳转语句 goto语句可以跳转到本函数内的某个标签   
    gotoCount := 0    
GotoLabel:    
    gotoCount++    
    if gotoCount < 10 {    
        goto GotoLabel //如果小于10的话就跳转到GotoLabel    
    }
break 标签除了可以跳出 for 循环,还可以跳出 select switch 循环, 参考下面代码:
L:   
    for ; count < 8192; count++ {    
        select {    
        case e := <-self.pIdCh:    
            args[count] = e 
        default:   
            break L // 跳出 select 和 for 循环    
        } 
}
参考:
译:go’s block and identifiers scope   
http://studygolang.com/articles/1438
标签:
原文地址:http://www.cnblogs.com/ghj1976/p/4283248.html