Home >Backend Development >Golang >How can I break out of a labeled for loop from outside its scope in Go?
Breaking Out of a Labeled For Loop from Outside Scope
In Go, it can be challenging to interrupt a labeled for loop from code that exists outside the loop's scope. This is common when using a go routine to perform periodic tasks and wanting to terminate the loop based on certain conditions.
Solution:
To achieve this, we can employ a signaling channel. Here's how to do it:
<code class="go">quit := make(chan struct{})</code>
A channel of type struct{}{} is used to send a signal that the loop should break. This channel is created outside the loop's scope.
When the condition is met to break the loop, we close the channel:
<code class="go">close(quit)</code>
By closing the channel, we signal that the go routine should terminate.
Inside the labeled for loop, incorporate a select statement to listen for the signal from the channel:
<code class="go">myLoop: for { select { case <-quit: break myLoop default: // Continue looping } }
When the quit channel is closed, the select statement detects this and executes the break statement, effectively breaking out of the loop.
<code class="go">go func (){ for { // Loop continues until count > 5 or quit channel is closed fmt.Println("I will print every second", count) count++ if count > 5 { close(quit) wg.Done() return } <-t.C } }()</code>
In this go routine, the select statement is not required because the loop is already run as a go routine and does not need to block.
By following these steps, you can break out of a labeled for loop from outside the loop's scope in Go using a signaling channel.
The above is the detailed content of How can I break out of a labeled for loop from outside its scope in Go?. For more information, please follow other related articles on the PHP Chinese website!