在结构体中嵌入通道

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

Embed channel in struct

问题

如何在Go中将通道嵌入到结构体中?

为什么在map语法中存在不一致性:

var m map[string]int

和通道,

var m chan int

为了澄清,Go语言中可以将一种类型嵌入到另一种类型中。嵌入类型可以访问嵌入类型上定义的所有方法,但也可以通过其类型名称显式地引用嵌入类型。因此,对于希望引用嵌入通道类型的人来说,map类型声明和通道类型声明之间的不一致性是令人困惑的。

英文:

How do I embed a channel in a struct in Go?

Why the inconsistency between the map syntax:

var m map[string]int

and channel,

var m chan int

?

To clarify, in Go it is possible to embed a type in another type. The embedder type gains access to all the methods defined on the embedded type, but it is also possible to refer to the embedded type explicitly by the name of its type. Therefore, the inconsistency between the map type declaration and channel type declaration is confusing for someone who would like to refer to an embedded channel type.

答案1

得分: 10

问题在于**嵌入**主要允许你从嵌入类型中受益(如在“在Go中使用嵌入代替继承”中所述)。

channel,就像map一样,是一个**无名类型**(使用类型字面量指定,它由现有类型组成一个新类型)。
它没有自己的方法或导出字段,所以在struct {}中嵌入channel类型并不会有太大作用。

你可能会得到类似于这个示例中的错误消息:

func (x chan int) m2() {}
invalid receiver type chan int (chan int is an unnamed type)

如果在struct类型中嵌入channel类型有效,那么该无名类型将能够作为方法的接收器,但似乎语言本身不允许这样做。

英文:

The problem is that embedding allows you mainly to benefit from the methods from the embedded type (as mentioned in "Embedding instead of inheritance in Go")

And channel, like map, is an unnamed type (specified using a type literal, which composes a new type from existing types.).
It doesn't have methods of its own, or exported fields, so you wouldn't go very far by embedding a channel type within a struct {}.

You would probably have an error message similar as the one in this example:

func (x chan int) m2() {}
invalid receiver type chan int (chan int is an unnamed type)

If embedding a channel type within a struct type worked, that unnamed type would be able to act as a receiver for methods, which doesn't seem to be allowed by the language in the first place.

huangapple
  • 本文由 发表于 2014年10月4日 23:11:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/26194122.html
匿名

发表评论

匿名网友

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

确定