英文:
Can you put channels in a channel in Go?
问题
你好!以下是你要翻译的内容:
你能在Go语言中创建一个通道的通道吗?
示例:
package main
func main() {
c := make(chan chan int)
go func() {
for i := 0; i < 10; i++ {
c <- addChannel()
}
}()
}
func addChannel() chan int {
d := make(chan int)
return d
}
我只是好奇,因为如果可能的话,这显然在Go编程中可能有一些用途。
英文:
Can you create a channel of channels in Go???<br>
example:
package main
func main() {
c := make(chan chan int)
go func() {
for i := 0; i < 10; i++ {
c <- addChannel
}
}()
}
func addChannel() chan int {
d := make(chan int)
return d
}
I'm just curious, because this obviously could serve some purpose in go programming if it is possible.
答案1
得分: 3
是的,你可以在代码中创建一个通道的通道。在这种情况下,你应该使用make(chan chan int)
来创建一个通道的通道,其中通道的类型是int
。以下是一个示例代码:
package main
import "fmt"
func main() {
c := make(chan chan int)
go func() {
for i := 0; i < 10; i++ {
c <- addChannel()
}
close(c)
}()
for ic := range c {
for z := range ic {
fmt.Println(z)
}
fmt.Println("done with channel")
}
}
func addChannel() chan int {
d := make(chan int)
go func() {
d <- 1
close(d)
}()
return d
}
你可以在这里找到这个示例的在线运行版本。
英文:
Yes you can; the the language specification is a good place to start when you have questions like this.
However while it's possible to create a channel of channels it's not possible to create a channel without a "channel type". So in your code you should use make(chan chan int)
that is a channel of channels of int
. For example (playground):
package main
import "fmt"
func main() {
c := make(chan chan int)
go func() {
for i := 0; i < 10; i++ {
c <- addChannel()
}
close(c)
}()
for ic := range c {
for z := range ic {
fmt.Println(z)
}
fmt.Println("done with channel")
}
}
func addChannel() chan int {
d := make(chan int)
go func() {
d <- 1
close(d)
}()
return d
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论