dreamy1992 2015-02-19 09:08
浏览 7
已采纳

返回频道Golang

I'm trying with Go channels and confused with below function example from go blog:

func gen(nums []int) <-chan int {
    out := make(chan int)
    go func() {
        for _, n := range nums {
            out <- n
        }
        close(out)
    }()
    fmt.Println("return statement is called ")
    return out
}

Main :

func main() {
    c := make(chan int)
    c = gen([]int{2, 3, 4, 5})

    // Consume the output.
    // Print 2,3,4,5
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
    fmt.Println(<-c)
}

Complete Code: http://play.golang.org/p/Qh30wzo4m0

My Doubts:

  1. My understanding was, once return is called the function will be terminated and the channel inside that function has no more life.

  2. The return statement is called only once. But the content of the out channel is read many times. In this case what is the actual flow of execution?

(I'm new to concurrent programming.)

  • 写回答

2条回答 默认 最新

  • 普通网友 2015-02-19 09:18
    关注
    out := make(chan int)
    

    This is not a buffered channel, which means the out <- n will block until someone somewhere reads that channel (the fmt.Println(<-c) calls)
    (See also "do golang channels maintain order")

    So the return at the end of the gen() function doesn't mean the literal go func() is terminated (since it is still waiting for readers to consume the content of the out channel).

    But main function getting out channel as return from gen() function.
    How it is possible to get it after gen() is terminated?

    The fact that gen() terminates has no effect on its returned value (the out channel): the goal of "gen()" is to "generate" that out channel.

    main can use out (as the returned value of gen()) long after gen() terminates.

    The literal go func within gen() still runs, even if gen() is terminated.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?