Idiom for exiting from for { select { ... } }?

What is the right way to instruct Go to leave a for { select { ... } } block? I tried break, but unfortunately break only leaves the inner select block, I think as a historical fact that break is associated with terminating case blocks within switches :frowning:

Should we declare a boolean variable and do for theVar { select { ... } }?

Use assembler labels?

Wrap in an anymous 0-ary function and immediately call it, with return keyword? Reeks of ECMAScript 3 nonsenseā€¦

A boolean variable is one option. Another might be to move some of the code into a function that you can return from. A third option, which is likely what you are looking for, is a label and a break label. Basically this is what they look like:

func main() {

// This is the label
	for {
		select {
		case <-done:
                    // This is the break with a label
			break PrintLoop
		case word := <-word:

You can see this actually being used here:

Note: The term ā€œlabelā€ is used in effective Go and should be accurate, but Iā€™m not 100% what to call a break statement with a label so I just go with ā€œbreak labelā€ or ā€œlabelled breakā€. If someone knows an official term please share it. calls it break label

Well, the labels must be used very carefuly and are very limited situations where a label is needed. Is better to use any other standard methods instead because jumping uncontrolled in your application can have unexpected results.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.