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
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…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With