返回频道Golang
我正在尝试使用Go频道并与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 } 主要: func main() { c := make(<-chan int) c = gen([]int{2,3,4,5}) // Consume the output.//Print 2,5 fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c) fmt.Println(<-c) } 完整代码:http://play.golang.org/p/Qh30wzo4m0 我怀疑: >我的理解是,一旦返回被调用,函数将被终止,并且该函数内的通道不再有生命. (我是并发编程的新手.) out := make(chan int) 这不是缓冲通道,这意味着out< - n将阻塞,直到有人在某处读取该通道(fmt.Println(< -c)调用) 因此,gen()函数结束时的返回并不意味着文字go func()被终止(因为它仍在等待读者使用out通道的内容).
gen()终止的事实对其返回值(out channel)没有影响:“gen()”的目标是“生成”该out channel. main可以在gen()终止后使用out(作为gen()的返回值). 即使gen()终止,gen()内的文字go func仍会运行. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |