doufuhuang6981 2016-10-21 16:31
浏览 65
已采纳

从函数获取响应而不返回-Golang

I have a service function in Golang where running an endless for loop. I wanted to get data from this function without return. What is the best solution, a channel, or io.Writer? The function and where I call it in a different package, because the funcion in package something while where I call it is the main. There is an example with channels:

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

On the otherside where I call this function:

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

In this case I only get the first message what the function take to the channel.

  • 写回答

1条回答 默认 最新

  • doudou1438 2016-10-21 16:46
    关注

    The channel is a good option. To read all messages, just read from channel in a loop until it closes:

    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

    Another option is passing a callback into the function:

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services