How Can You Halt a Go For Loop Externally?

Barbara Streisand
Release: 2024-10-26 09:52:29
Original
675 people have browsed it

How Can You Halt a Go For Loop Externally?

Halting a For Loop's Execution Externally in Go

In Go, you may encounter scenarios where you need to terminate the execution of a for loop from outside its scope. For instance, you might have a long-running loop that needs to be interrupted when a specific condition is met.

To achieve this, you can leverage a signaling channel. Here's how it works:

Creating a Signaling Channel

<code class="go">quit := make(chan struct{}{})</code>
Copy after login

This line creates a channel with an empty struct as its value type. It will be used to signal the loop to stop.

Closing the Channel

Within the goroutine that is running the loop, you can use the close function to close the signaling channel when the desired condition is met:

<code class="go">if count > 5 {
  close(quit)
  wg.Done()
  return
}</code>
Copy after login

Reading from the Closed Channel

When the quit channel is closed, reading from it returns immediately with a zero value. This behavior is exploited in the outer loop. By default, reading from a closed channel blocks indefinitely. However, this can be circumvented using a select statement:

<code class="go">myLoop:
for {
  select {
  case <-quit:
    break myLoop
  default:
    fmt.Println("iteration", i)
    i++
  }
}</code>
Copy after login

In this select statement, the default case continues the loop iteration as expected. When the quit channel is closed, the first case is satisfied, causing the loop to break immediately.

By using a signaling channel, you can effectively stop the execution of a for loop from an external function or goroutine when necessary, ensuring greater flexibility and control over your code execution.

The above is the detailed content of How Can You Halt a Go For Loop Externally?. 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!