SoFunction
Updated on 2025-03-01

Golang Advanced break usage instructions for breaking out of multiple loops

In the process of writing code, you will inevitably encounter loop nesting operations. The most troublesome thing at this time is that you need to exit layer by layer or use goto statements when breaking. Golang has a high-level break usage similar to goto but is more friendly and easier to read, which is the way to use label outside the loop to exit which layer of loop to exit.

Sample code:

I:
 for i := 0; i < 2; i++ {
 for j := 0; j < 5; j++ {
 if j == 2 {
 break I
 }
 ("hello")
 }
 ("hi")
 }

Program running results:

hello

hello

Supplement: How to break outer loop in golang for select body

question

By default, break in select only breaks the select body, instead of ending the for loop

for {
 select{
 case &lt;-:
  //do someting
 case &lt;- stop:
  break //The break is not a for loop, but a break is out of select and execute doNext() }
 doNext()
}

How to break to outer loop in the for select body?

1. Solution

1.1 Using a tagged break

LOOP: for {
 select{
 case &lt;-:
  //do someting
 case &lt;- stop:
  break LOOP//break's for loop, jump to doOther() }
 doNext()
}
doOther()

It is equivalent to goto of C, but it is different. For example, the tag before the for loop here will cause the loop to be executed again if you use goto LOOP. But golang's break here jumps out of the loop and executes the operation after the loop

1.2 Using return

for {
 select{
 case &lt;-:
  //do someting
 case &lt;- stop:
  return //Clean and neat, suitable for exiting goroutin scenarios }
 doNext()
}
doOther()

1.3 Use the logo

isStop := false
for {
 select{
 case &lt;-:
  //do someting
 case &lt;- stop:
  isStop = true//Clean and neat, suitable for exiting goroutin scenarios  break
 }
 if isStop {
 break
 }
 doNext()
}
doOther()

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.