在没有 return 的情况下从函数获取响应 - Golang

Getting response from function without return - Golang

我在 Golang 中有一个服务函数,其中 运行 一个无限循环。我想在没有 return 的情况下从此函数获取数据。什么是最佳解决方案、渠道或 io.Writer?函数和我在不同的包中调用它的地方,因为 package something 中的函数而我调用它的地方是主要的。有一个频道示例:

func Check(dst string, w chan string) bool {    
  for {
    w <- data
  }
  return false
}

在我调用这个函数的另一边:

var wg sync.WaitGroup
func main() {
    messages := make(chan string, 10)

    wg.Add(3)
    go checking("10.1.1.1", messages)
    msg := <-messages
    fmt.Println(msg)
    wg.Wait()
}

func checking(ip string, msg chan string) {
    defer wg.Done()
    w := worker.ContainerAliveIndicator{}
    w.Check(ip, msg)
}

在这种情况下,我只收到函数传送到频道的第一条消息。

频道是个不错的选择。要读取所有消息,只需循环读取通道直到它关闭:

func check(s string, ch chan<- string) {
    for i := 0; i < 5; i++ { 
        //this could go forever, or until some condition is met
        ch <- fmt.Sprintf("I did something %s %d", s, i)
        time.Sleep(time.Millisecond)
    }
    close(ch)
}

func main() {
    ch := make(chan string)
    go check("FOO", ch)
    for msg := range ch { //will break when ch closes
        fmt.Println(msg)
    }
    fmt.Println("DONE!")
}

playground

另一个选项是将回调传递给函数:

func check(s string, cb func(string)) {
    for i := 0; i < 5; i++ { 
        //this could go forever, or until some condition is met
        cb(fmt.Sprintf("I did something %s %d", s, i))
        time.Sleep(time.Millisecond)
    }
}

func main() {
    msgs := []string{}
    check("FOO", func(s string) { msgs = append(msgs, s) })
    fmt.Println(msgs)
}

playground