doukui4786
2017-10-17 14:06
浏览 74
已采纳

标签-中断vs继续vs goto

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条回答 默认 最新

  • doufu9521 2017-10-17 14:17
    已采纳

    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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题