首页 > 解决方案 > 如何在不运行以下脚本的情况下退出循环

问题描述

我想从第二个循环跳到第一个循环(比如休息),但休息后我不想打印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)
    }
}

标签: loopsgobreak

解决方案


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

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

要使用语句解决外部循环,请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总是从最内层循环中断(更具体地说是 a或) for,因此之后外层循环将继续其下一次迭代。switchselect

如果您有嵌套循环,并且您想从外部循环中断内部循环,则必须使用标签:

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

推荐阅读