如何在内部循环中跳出外部循环。

huangapple go评论79阅读模式
英文:

how to break the outer loop within the inner loop

问题

for i := 0; i < 5; i++ {
    fmt.Println("i is", i)
    for j := 0; j < 3; j++ {
        if j == 2 {
            break
        }
        fmt.Println("j is", j)
        if i == 2 {
            break
        }
    }
}

我想让这段代码在 i 等于 2 的时候中断程序。我该如何在内部循环中发出信号,以中断外部循环?

我无法弄清楚如何中断或继续外部循环。

英文:
for i := 0; i &lt; 5; i++ {
		fmt.Println(&quot;i is&quot;, i)
		for j := 0; j &lt; 3; j++ {
			if j == 2 {
				break
			}
			fmt.Println(&quot;j is &quot;, j)
		}
	}

I want this code to break the program if the i was equal to 2. how can I signal that I wanna break the outer loop within the inner loop ?

I can't figure it out how to break or continue the outer loop

答案1

得分: 2

这是答案。你可以在Go语言中使用标签来引用不同的循环。

英文:
outerLoop:
	for i := 0; i &lt; 5; i++ {
		for j := 0; j &lt; 3; j++ {
			if i == 3 {
				break outerLoop
			}
			fmt.Println(i, j)
		}
	}

here is the answer . you can use labels in Go to refer to different loops

huangapple
  • 本文由 发表于 2023年2月14日 16:21:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75445044.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定