Home  >  Article  >  Backend Development  >  How to Break an Infinite For Loop from an External Scope in Golang?

How to Break an Infinite For Loop from an External Scope in Golang?

Susan Sarandon
Susan SarandonOriginal
2024-10-26 09:37:29757browse

How to Break an Infinite For Loop from an External Scope in Golang?

Breaking a For Loop from Outside 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn