break in the flow control language Go, continue and goto (seven)

BREAK (out of the loop)

break out for the entire cycle, as follows:

func main() {
    for i:=0;i<10;i++{
        if i>3{
            break
        }
        fmt.Println(i)
    }
}

// 0 1 2 3

3 to print only the code, will be greater than when the entire out of for loop 3, note that the entire loop for the direct comprising break means a layer of a for loop that, for example:

func main() {
    for i:=0;i<10;i++{
        for j:=0;j<10;j++ {
            if j == 5 {
                break
            }
            fmt.Printf("%v-%v\n",i, j)
        }
    }
}

See the results of the code above, the inner loop will only print found to 4, 9 to the outer layer may be circular (i.e., for the entire cycle has completed).

 

In addition, we can also use tags to specify the exit loop . The above transformation of the double loop code, as follows:

func main() {
    EX:
    for i:=0;i<10;i++{
        for j:=0;j<10;j++ {
            if j == 5 {
                break EX
            }
            fmt.Printf("%v-%v\n",i, j)
        }
    }
}

I added a label EX in the outermost for loop above, then break EX, this time the result is when j == 5, the exit from the outermost for loop here. For comparison, the can try:

func main() {
    for i:=0;i<10;i++{
        EX:
        for j:=0;j<10;j++ {
            if j == 5 {
                break EX
            }
            fmt.Printf("%v-%v\n",i, j)
        }
    }
}

In fact, such an approach is not tagged with the same effect, also when it comes to the top, break that contains it to exit the current cycle.

 

continue (continue to the next cycle)

continue to continue to the next cycle, the difference between the break is not out of the whole cycle, just skip this cycle:

main FUNC () {
     for I: = 0 ; I < 10 ; I ++ {
         IF I == 5 {
             Continue 
        } 
        fmt.Println (I) 
    } 
} 

// skip cycle 5, the latter continues
 // 0123 46789

 

continue also support label wording:

func main() {
    EX:
    for i:=0;i<10;i++{
        for j:=0;j<10;j++ {
            if j == 5 {
                continue EX
            }
            fmt.Printf("%v-%v\n",i, j)
        }
    }
}

 

goto (jump to a specified label)

goto is a good thing that we can jump to the specified label, to perform that part of the code example:

func main() {
    for i:=0;i<10;i++{
        for j:=0;j<10;j++ {
            if j == 5 {
                goto breakTag
            }
            fmt.Printf("%v-%v\n",i, j)
        }
        breakTag:
            break
    }
}

Code above, when j == 5 when using breakTag goto jump to the label, the break is performed (note that break position) under the label, so that for the outermost loop interrupt is not very good.

Guess you like

Origin www.cnblogs.com/wjaaron/p/11496696.html