The following code waits for the 'results' channel to be empty and then the DEFAULT branch breaks to Label DONE.
Now the question: Why does this break the FOR LOOP?? It seems that the FOR loop would continue to skip to DEFAULT and never end.
WHAT IS BREAKING THE FOR LOOP.
The Output is as follows:
Break DONE
End For
...
DONE:
for {
select { // Nonblocking
case result := <-results:
fmt.Printf("%s:%d:%s
", result.filename, result.lino,
result.line)
default:
fmt.Println("Break DONE")
break DONE
}
fmt.Println("END Select")
}
fmt.Println("End For")
The confusion comes from the idea that you're going to block there on the first case. That's not what happens. You iterate the select options indefinitely taking the one available until you encounter the break. In this case, it would indicate there is nothing to receive from the results
channel on your first iteration so it automatically falls into the default cause, prints Break DONE
and you're done.
break DONE
is not the same as goto DONE
in C or other languages. The label marks the for loop which break DONE
statement will terminate when executed. It doesn't jump to DONE
label, it terminates the for loop marked with the DONE
label. Labeled breaks are very usefull when you want to break from nested loops or, like in your case, terminate loop from inside of select. Without a label break would only terminate select.
the break keyword used terminate the execution, when you debug this code, the default option will selected and then break keyword perform which stop the program. Program will not able go at DONE label
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.
https://golang.org/ref/spec#Break_statements
The label in this example explicitly marks the "for" to terminate.