Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

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

like image 509
Dan Avatar asked Jun 24 '14 08:06

Dan


1 Answers

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…

like image 137
Elwinar Avatar answered Sep 25 '22 10:09

Elwinar