【发布时间】:2020-04-24 09:21:49
【问题描述】:
我正在学习 golang 一段时间。我遇到了频道问题。 我有2个例子。它们看起来相同,但其中 1 个给出错误。 当我分配通道容量(转换为缓冲通道)时,问题正在解决,但其他示例没有容量分配。
这是我的第一个问题。
第一个代码https://play.golang.org/p/dbC7ZZsagin
// Creating a channel
// Using make() function
mychnl := make(chan string)
// Anonymous goroutine
go func() {
mychnl <- "GFG"
mychnl <- "gfg"
mychnl <- "Geeks"
mychnl <- "GeeksforGeeks"
close(mychnl)
}()
// Using for loop
for res := range mychnl {
fmt.Println(res)
}
第二个代码https://play.golang.org/p/yQMclmwOYs9
// We'll iterate over 2 values in the `queue` channel.
queue := make(chan string, 2)
queue <- "one"
queue <- "two"
close(queue)
// This `range` iterates over each element as it's
// received from `queue`. Because we `close`d the
// channel above, the iteration terminates after
// receiving the 2 elements.
for elem := range queue {
fmt.Println(elem)
}
如果您在第二个代码处删除容量编号,程序将无法运行,我不知道为什么。我想也许对于范围迭代,有必要分配一个容量值,但还有另一个代码可以工作。
从现在开始谢谢。
【问题讨论】: