首頁  >  文章  >  後端開發  >  如何在 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