英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论