Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Loops 如何在不运行下面的脚本的情况下退出循环_Loops_Go_Break - Fatal编程技术网

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

Loops 如何在不运行下面的脚本的情况下退出循环,loops,go,break,Loops,Go,Break,我想从第二个循环到第一个循环,就像break一样,但是在break之后我不想打印fmt.println i的值是,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一样,但是在break之后我不想打印fmt.println i的值是,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)
    }
原始答复:

break总是从最里面的循环(更具体地说是for、switch或select)中断,因此在这之后,外部循环将继续其下一次迭代

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

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)
        }
    }
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)
        }
    }
The value of j is 0
The value of j is 1
Breaking out of loop