loops - 标签 - break vs continue vs goto

标签 loops go goto

我的理解是:

break - 停止进一步执行循环结构。

continue - 跳过循环体的其余部分并开始下一次迭代。

但是当与标签结合使用时,这些陈述有何不同?

换句话说,这三个循环有什么区别:

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

输出:

0 1 2 3 4


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

输出:

0 1 2 3 4 6 7 8 9


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

输出:

0 1 2 3 4 0 1 2 3 4 ...(无限)


最佳答案

对于 breakcontinue,附加标签可让您指定要引用的循环。例如,您可能想要break/continue 外循环而不是您嵌套的循环。

这是来自 Go Documentation 的示例:

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

即使当前正在迭代行中的列(数据),这也能让您进入下一个“行”。这是有效的,因为标签 RowLoop 通过直接在外循环之前“标记”外循环。

break 可以以相同的方式使用相同的机制。这是来自 Go Documentation 的示例for when break 语句对于在 switch 语句内部跳出循环很有用。如果没有标签,go 会认为您正在跳出 switch 语句,而不是循环(这就是您想要的,在这里)。

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
            }
        }
    }

对于goto,这是比较传统的。它使程序执行 Label, next 处的命令。在您的示例中,这会导致无限循环,因为您会反复进入循环的开头。

文档时间

对于 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.

对于 continue :

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

关于loops - 标签 - break vs continue vs goto,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46792159/

相关文章:

c - 转到内部开关盒工作异常

python - 循环遍历目录以查找匹配的文件

java - 尝试输入带有空格的字符串时出现 InputMismatchException

python - 如何在Python中循环遍历另一个数组内的一个数组的长度?

go - 相当于 json marshal 的 Stringer

objective-c - 如何在 objective-c 中使用goto语句?

excel - Excel VBA中不存在选项卡时的错误处理

go - 类型、接口(interface)和指针

go - 找不到 GOPATH 甚至设置 env 路径

c++ - 我应该在这里使用 goto 语句吗?