go routine for range over channels

前端 未结 3 1088
孤街浪徒
孤街浪徒 2021-01-15 17:04

I have been working in Golang for a long time. But still I am facing this problem though I know the solution to my problem. But never figured out why is it happening.

<
3条回答
  •  不知归路
    2021-01-15 17:28

    Your function creates a channel, writes to it, then returns it. The writing will block until somebody can read the corresponding value, but that's impossible because nobody outside this function has the channel yet.

    func sq(in <-chan int) <-chan int {
        // Nobody else has this channel yet...
        out := make(chan int)
        for n := range in {
            // ...but this line will block until somebody reads the value...
            out <- n * n
        }
        close(out)
        // ...and nobody else can possibly read it until after this return.
        return out
    }
    

    If you wrap the loop in a goroutine then both the loop and the sq function are allowed to continue; even if the loop blocks, the return out statement can still go and eventually you'll be able to connect up a reader to the channel.

    (There's nothing intrinsically bad about looping over channels outside of goroutines; your main function does it harmlessly and correctly.)

提交回复
热议问题