为什么这段代码不会无限循环并使用break标签?

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

Why doesn't this code loop forever with a break label?

问题

我正在尝试弄清楚带标签的break语句是如何工作的。

我期望以下程序会一直打印"In if statement"。这是因为break here语句将代码执行返回到for循环的开头,然后再次执行。

然而,这段代码只执行一次。我在这里漏掉了什么?

package main

import "fmt"

func main() {
here:
	for {
		fmt.Println("In if statement")
		break here

	}
	fmt.Println("At the bottom")
}

执行结果:

In if statement
At the bottom

程序已退出。

链接:http://play.golang.org/p/y9kH1YZezJ

英文:

I am trying to figure out how break with labels works.

I expect the following program to keep printing "In if statement" forever. This is because the break here statement brings the code execution back up to the beginning for loop which should then be executed again and again.

However, this code is only executed once. What am I missing here?

package main

import "fmt"

func main() {
here:
	for {
		fmt.Println("In if statement")
		break here

	}
	fmt.Println("At the bottom")
}

Execution result:

In if statement
At the bottom

Program exited.

http://play.golang.org/p/y9kH1YZezJ

答案1

得分: 9

根据Go语言规范中关于"break语句"的说明:

如果有一个标签,那么它必须是一个包围着"for"、"switch"或"select"语句的标签,并且它是终止执行的那个语句

break语句并不会将代码返回到标签处,它只是终止由标签引用的循环。所以一切都正常运行...

英文:

From the go specification on break statements:

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

The break statement doesn't bring your code back to the label, it close the loop referenced by the label. So everything is working fine…

答案2

得分: 8

这是因为break语句将代码执行带回到标记的循环的开头。

不,break并不是goto语句。它是用来退出标记的循环的。执行会继续在循环之后进行。

在这个特定的例子中,标记是不必要的,你可以默认地通过break语句退出最内层的循环来达到相同的结果(无需使用标记)。

英文:

> This is because the break here statement brings the code execution back up to the beginning for loop

No, that is not what break does. It is not a goto. It exits the loop marked with the label. Execution continues after the loop.

In this particular example, the label is unneccessary, you would be getting the same result by breaking out of the innermost loop by default (without a label).

huangapple
  • 本文由 发表于 2014年6月24日 16:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/24381799.html
匿名

发表评论

匿名网友

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

确定