为什么我不能将类型 []chan *Message 用作函数参数中的类型 []chan interface{}?

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

Why can't I use type []chan *Message as type []chan interface{} in a function argument?

问题

这是我得到的错误信息:

在函数参数中,无法将c.ReceiverChans(类型为[]chan *Message)用作类型[]chan interface {}。

英文:

This is the error message I am getting:

> cannot use c.ReceiverChans (type []chan *Message) as type []chan interface {} in function argument

答案1

得分: 2

类型是不同的。*Message 实现了空接口,但这并不意味着你可以将 *Message 的切片或通道传递给期望接口的切片或通道的函数。

我将接口视为一种特定的数据结构;一个指向值的指针和一个指向底层类型的指针的组合。这并不完全是接口的工作原理,但这有助于我的直觉。使用这种直觉,如果我将一个 int 传递给一个期望 interface{} 的函数,我会想象在函数调用之前,编译器会将我的值隐式地包装在这个接口对中。如果相反,函数期望一个 []interface{},而我想传递一个 []int,编译器该怎么办呢?它将不得不构造一个新的接口对数组,但这样做既昂贵,而且实际上行不通,因为如果例如切片被排序,原始切片将保持不变。

这是 golang FAQ 中的问题:http://golang.org/doc/faq#convert_slice_of_interface

这是 go wiki 上关于接口切片的更详细解释,比我刚才说的更好理解。
https://code.google.com/p/go-wiki/wiki/InterfaceSlice

英文:

The types are different. A *Message implements the empty interface, but that doesn't mean you can take a slice or chan of *Message and pass it to something that expects a slice or chan of interfaces.

The way I think of interfaces as a particular data structure; a pair of a pointer to a value and a pointer to the underlying type. It's not exactly how interfaces work, but it helps my intuition. Using this intuition, if I pass an int, say, to a function that wants an interface{}, I imagine my value getting wrapped inside this interface pair implicitly by the compiler before the function's called. If instead, the function expects a []interface{}, and I want to pass a []int, what can the compiler do? It would have to construct a new array of the interface pairs, but then (a) that'd be expensive, and (b) it wouldn't really work, since if for example the slice got sorted, the original slice would be left alone.

Here's the question in the golang FAQ: http://golang.org/doc/faq#convert_slice_of_interface

Here's a more detailed explanation about slices of interfaces from the go wiki which explains better than I just did.
https://code.google.com/p/go-wiki/wiki/InterfaceSlice

huangapple
  • 本文由 发表于 2013年9月15日 16:05:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/18810267.html
匿名

发表评论

匿名网友

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

确定