Send channel through a channel with Go

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

Send channel through a channel with Go

问题

我想通过一个通道发送一个指向通道的指针。在Go语言中是否可能?如何定义接受这样的通道的函数?

我尝试了以下方式:

func test() (chan *chan)
func test() (chan chan)

请注意,以上代码是无效的。在Go语言中,不能直接定义一个接受通道指针的通道。通道是一种类型,而不是指针类型。你可以定义一个接受通道的函数,但不能定义一个接受通道指针的函数。如果你需要在通道之间传递指针,可以考虑将指针封装在结构体中,然后通过通道传递结构体的实例。

英文:

I'd like to send a pointer to a channel through a channel. Is it possible in Go? How to define function that accepts such channel?

I tried:

func test() (chan *chan)
func test() (chan chan)

答案1

得分: 10

每个通道都与一种类型相关联。假设该类型为T。T类型的通道是:

chan T

指向T类型通道的指针是:

*chan T

指向指向T类型通道的指针的通道是:

chan *chan T

接受指向指向T类型通道的指针的通道的函数是:

func f(c chan *chan T) { }

因为通道是引用类型,所以你可能不需要使用指针。可以尝试使用

func f(c chan chan T) { }

playground示例

英文:

There is always some type associated with a channel. Let's assume that the type is T. A channel of T is:

chan T

A pointer to a channel of T is:

*chan T

A channel of pointer to channel of T is:

chan *chan T

A function accepting the channel of pointer to channel of T is:

func f(c chan *chan T) { }

Because channels are reference types, you probably don't need to use a pointer. Try using

 func (f c chan chan T) { }

<kbd>playground example</kbd>

huangapple
  • 本文由 发表于 2015年3月18日 06:11:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/29110710.html
匿名

发表评论

匿名网友

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

确定