首页  >  文章  >  后端开发  >  如何从外部函数跳出 Go 中的 For 循环?

如何从外部函数跳出 Go 中的 For 循环?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 07:20:28147浏览

How Can I Break Out of a For Loop in Go from an External Function?

从外部中断 For 循环执行:Go 编程解决方案

在编程中,通常需要控制执行流程,特别是在管理循环时。在 Go 中,人们可能会遇到需要从外部源终止无限 for 循环的情况。本文通过提供全面的解决方案来解决此特定场景。

问题描述:

考虑带有标签的无限 for 循环,与计划函数同时运行。目标是当预定函数内满足特定条件时打破循环。下面是此类尝试的一个示例,由于范围限制而失败:

<code class="go">package main

import (
  "fmt"
  "sync"
  "time"
)

func main() {
  count := 0
  var wg sync.WaitGroup
  wg.Add(1)
  t := time.NewTicker(time.Second * 1)

  go func() {
    for {
      fmt.Println("I will print every second", count)
      count++
      if count > 5 {
        break myLoop; // Issue due to scope error: 'myLoop' not visible
        wg.Done()
      }
      <-t.C
    }
  }()

  i := 1

  myLoop:
  for {
    fmt.Println("iteration", i)
    i++
  }

  wg.Wait()
  fmt.Println("I will execute at the end")
}

解决方案:

为了实现此所需的功能,我们采用信令通道。以下是逐步细分:

1.创建一个信令通道:

我们创建一个 chan struct{} 类型的信令通道退出。该通道充当循环何时应终止的信号。

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

2.关闭信号中断通道:

当预定函数内满足条件时,我们关闭信号通道。这表明 for 循环应该中断。

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

3.检查通道是否关闭以打破循环:

在 for 循环中,我们使用 select 语句从信令通道读取数据。当通道关闭(发出中断信号)时,执行分支到 case

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

该解决方案有效地允许我们从其自身范围之外控制循环的执行,从而可以在需要时终止循环,而不必担心范围限制。

以上是如何从外部函数跳出 Go 中的 For 循环?的详细内容。更多信息请关注PHP中文网其他相关文章!

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