首页  >  文章  >  后端开发  >  如何在 Golang 中打破外部作用域的无限 For 循环?

如何在 Golang 中打破外部作用域的无限 For 循环?

Susan Sarandon
Susan Sarandon原创
2024-10-26 09:37:29757浏览

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

在 Golang 中从外部中断 For 循环

在嵌套函数中使用无限 for 循环时,会出现从外部作用域终止循环执行的挑战。当调度函数作为 goroutine 同时执行时,这一点尤其重要。

要解决这个问题,请考虑实现一个信号通道:

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

此通道将充当一个标志,指示循环何时应该进行

在 goroutine 中,不断地监视一个条件,当满足时,关闭信号通道:

<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>

同时,在无限 for 循环中,引入一个 select 语句来监视信号通道:

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

检测到关闭的信号通道后,select 语句立即将执行传递到默认情况,从而触发循环终止。

以上是如何在 Golang 中打破外部作用域的无限 For 循环?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn