在Go语言中,可以将通道放入另一个通道中。

huangapple go评论82阅读模式
英文:

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 &lt; 10; i++ {
			c &lt;- 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 &quot;fmt&quot;

func main() {
	c := make(chan chan int)
	go func() {
		for i := 0; i &lt; 10; i++ {
			c &lt;- addChannel()
		}
		close(c)
	}()

	for ic := range c {
		for z := range ic {
			fmt.Println(z)
		}
		fmt.Println(&quot;done with channel&quot;)
	}
}
func addChannel() chan int {
	d := make(chan int)
	go func() {
		d &lt;- 1
		close(d)
	}()
	return d
}

huangapple
  • 本文由 发表于 2022年6月6日 08:47:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/72512053.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定