Home >Backend Development >Golang >How to Break an Infinite For Loop from an External Scope in Golang?
When utilizing infinite for loops within nested functions, the challenge arises in terminating the loop's execution from an external scope. This is particularly relevant when scheduled functions execute concurrently as goroutines.
To address this, consider implementing a signaling channel:
<code class="go">quit := make(chan struct{})</code>
This channel will act as a flag to indicate when the loop should break.
Within the goroutine, diligently monitor a condition that, when satisfied, closes the signaling channel:
<code class="go">go func () { for { fmt.Println("I will print every second", count) count++ if count > 5 { close(quit) wg.Done() return } <-t.C } }()</code>
Simultaneously, within the infinite for loop, introduce a select statement that monitors the signaling channel:
<code class="go">myLoop: for { select { case <-quit: break myLoop default: fmt.Println("iteration", i) i++ } }</code>
Upon detecting a closed signaling channel, the select statement immediately passes execution to the default case, triggering the loop's termination.
The above is the detailed content of How to Break an Infinite For Loop from an External Scope in Golang?. For more information, please follow other related articles on the PHP Chinese website!