douao3063 2018-01-31 14:04
浏览 29
已采纳

为什么我需要对go例程/通道的结果进行额外的for循环以显示所有结果?

A quick explanation of the code:

  • I'm ranging over db.Feeds() which is a list of RSS feed urls.
  • I'm getting the feeds in the getFeeds() function via a goroutine
  • The output of getFeeds() is returned into the rss channel
  • I then print the RSS information

    func main() {
        rss := make(chan feed)
    
        for _, url := range db.Feeds() {
            go getFeeds(url, rss)
        }
    
        for range db.Feeds() {
            newFeed := <-rss
            fmt.Println(newFeed.Channel.Title, newFeed.Channel.Description)
        }
    }
    

My question is as follows: When I directly print the newFeed variable it doesn't display all results from the rss channel, only the first one.

I seem to have to range over db.Feeds() (the list of RSS feed urls) and print the channel results from the for loop containing the go getFeeds() for it to display all the results.

Why is this the case? I would have though for each loop of the range, it would return into the rss channel and print the results without having to range over db.Feeds() a second time?

Any clarification greatly helped, I'm new to Go! Loving it, but not got my head around some aspects of the language yet.

  • 写回答

1条回答 默认 最新

  • dongmi3203 2018-01-31 14:08
    关注

    The <-channel operator consumes a single element from a channel. If you want to keep reading until the channel is closed, you need to range over it.

    However, you need to range over the channel itself, not db.Feeds:

    for newFeed := range rss {
        fmt.Println(newFeed.Channel.Title, newFeed.Channel.Description)
    }
    

    Technically, repeating the read newFeed := <-rss multiple times is what is really working.

    Currently, this only works because you have the same number of feeds as you have elements written to rss. If instead the number of elements did not match, you would either exit before reading all elements, or wait for more when there are no more coming.

    You'll also want some type of coordination to make sure you close the rss channel when all getFeeds functions are done.

    I strongly recommend you take the Go tour, especially the concurrency section

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog