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:
My understanding was, once
return
is called the function will be terminated and the channel inside that function has no more life.The
return
statement is called only once. But the content of theout
channel is read many times. In this case what is the actual flow of execution?
(I'm new to concurrent programming.)