go channel take empty struct as input. Can this input be anything?

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

go channel take empty struct as input. Can this input be anything?

问题

a := make(chan struct{})

这样,Go 通道以空结构作为输入。这个输入可以是任何东西吗?

谢谢。

英文:

a := make(chan struct{})

Such this, go channel take empty struct as input. Can this input be anything?

thanks.

答案1

得分: 5

不:它可以是一个空结构体(struct{}{}),而不是“任何东西”。

要表示“任何东西”,你需要使用interface{}

正如我在“Go Golang:匿名结构体和空结构体”中解释的那样,空结构体在传递大小为0的对象时非常有用!这是一种很好的方式来表示某件事情已经完成。

英文:

No: it can be an empty struct (struct{}{}), not "anything"

To be "anything", you would need interface{}.

As I explain in "Go Golang : anonymous struct and empty struct", an empty struct is useful to pass an object of size... 0! It is a good way to signal the completion that something has happened.

答案2

得分: 0

struct{}在其他语言中类似于单位类型(unit type),它只有一个没有信息的值。从这样的通道获取的值不包含任何信息,但是可以将这样的通道用于在某个事件发生时进行信号传递。当有东西发送到该通道时,接收该通道的goroutine会被唤醒。

英文:

struct{} is much like the unit type in other languages; it only has one value with no information. The values you get from such a channel would contain no information, but such a channel could be used for signalling when some event happened. A goroutine receiving from that channel would wake up whenever something is sent to it.

huangapple
  • 本文由 发表于 2014年8月28日 14:11:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/25541866.html
匿名

发表评论

匿名网友

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

确定