问题描述
如何在结构中嵌入频道?
为什么地图语法不一致:
var m map [string ]
和频道
<$ p $
$
为了澄清,在Go中可以嵌入另一种类型的类型。嵌入类型可以访问嵌入类型中定义的所有方法,但也可以通过类型的名称显式引用嵌入类型。因此,地图类型声明和通道类型声明之间的不一致对于想要引用嵌入式通道类型的用户来说是令人困惑的。 解决方案
如何在结构中嵌入频道?
为什么地图语法不一致:
var m map [string ]
和频道
<$ p $
$
为了澄清,在Go中可以嵌入另一种类型的类型。嵌入类型可以访问嵌入类型中定义的所有方法,但也可以通过类型的名称显式引用嵌入类型。因此,地图类型声明和通道类型声明之间的不一致对于想要引用嵌入式通道类型的用户来说是令人困惑的。 解决方案
问题在于 允许您主要从嵌入式类型的方法中受益(如)
以及,例如是 (使用类型文字指定,它从现有类型组成了一个新类型)。
它没有i的方法你自己或导出的字段,所以你不会在 struct {} 类型>。
您可能会收到类似于:
func(x chan int)m2(){}
无效接收器类型chan int(chan int是未命名类型)
如果嵌入 channel 类型在 struct 类型中工作,那么这个未命名的类型可以作为,这似乎不被语言所允许的。
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.
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.
这篇关于在通道中嵌入通道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!