Labels - break vs continue vs goto

2020-06-12 06:38发布

问题:

I understand that:

break - stops further execution of a loop construct.

continue - skips the rest of the loop body and starts the next iteration.

But how do these statements differ when used in combination with labels?

In other words what is the difference between these three loops:

Loop:
    for i := 0; i < 10; i++ {
        if i == 5 {
             break Loop
        }
        fmt.Println(i)
    }

Output:

0 1 2 3 4


Loop:
    for i := 0; i < 10; i++ {
        if i == 5 {
             continue Loop
        }
        fmt.Println(i)
    }

Output:

0 1 2 3 4 6 7 8 9


Loop:
    for i := 0; i < 10; i++ {
        if i == 5 {
             goto Loop
        }
        fmt.Println(i)
    }

Output:

0 1 2 3 4 0 1 2 3 4 ... (infinite)


回答1:

For break and continue, the additional label lets you specify which loop you would like to refer to. For example, you may want to break/continue the outer loop instead of the one that you nested in.

Here is an example from the Go Documentation:

RowLoop:
    for y, row := range rows {
        for x, data := range row {
            if data == endOfRow {
                continue RowLoop
            }
            row[x] = data + bias(x, y)
        }
    }

This lets you go the the next "row" even when your currently iterating over the columns (data) in the row. This works because the label RowLoop is "labeling" the outer loop by being directly before it.

break can be used in the same way with the same mechanics. Here is an example from the Go Documentation for when a break statement is useful for breaking out of a loop when inside of a switch statement. Without the label, go would think you were breaking out of the switch statement, instead of the loop (which is what you want, here).

OuterLoop:
    for i = 0; i < n; i++ {
        for j = 0; j < m; j++ {
            switch a[i][j] {
            case nil:
                state = Error
                break OuterLoop
            case item:
                state = Found
                break OuterLoop
            }
        }
    }

For goto, this is more traditional. It makes the program execute the command at the Label, next. In your example, this leads to an infinite loop since you go to the beginning of the loop, repeatedly.

Documentation Time

For break:

If there is a label, it must be that of an enclosing "for", "switch", or "select" statement, and that is the one whose execution terminates.

For continue:

If there is a label, it must be that of an enclosing "for" statement, and that is the one whose execution advances.



标签: loops go goto