如何在没有 运行 下面的脚本的情况下退出循环

How to out from looping without running the script below

我想从第二个循环跳出到第一个循环(比如 break)但是在 break 之后我不想打印 fmt.Println("The value of i is", i)。算法怎么样?

package main

import "fmt"

func main() {
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                break
            } else {
                fmt.Println("j = ", j)
            }
        }
        fmt.Println("The value of i is", i)
    }
}

编辑:您编辑了您的代码,所以这里是编辑后的答案。

要从内部继续外部循环(打破内部循环并跳过外部循环的其余部分),您必须继续外部循环。

要使用 continue 语句处理外循环,请使用标签:

outer:
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                continue outer
            } else {
                fmt.Println("j = ", j)
            }
        }
        fmt.Println("The value of i is", i)
    }

这将输出(在 Go Playground 上尝试):

j =  0
j =  1
Breaking out of loop
j =  0
j =  1
Breaking out of loop

原回答:

break 总是从最内层循环中断(更具体地说是 forswitchselect),所以在那之后外层循环将继续其下一个迭代。

如果你有嵌套循环并且你想从一个内循环中脱离外循环,你必须使用标签:

outer:
    for i := 0; i < 2; i++ {
        for j := 0; j < 4; j++ {
            if j == 2 {
                fmt.Println("Breaking out of loop")
                break outer
            }
            fmt.Println("The value of j is", j)
        }
    }

这将输出(在 Go Playground 上尝试):

The value of j is 0
The value of j is 1
Breaking out of loop