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

Susan Sarandon
Release: 2024-10-26 09:37:29
Original
766 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!