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 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网