英文:
Cannot pass chan implementation to method requiring chan interface
问题
我有一个接口X和一个名为Y的X实现。
问题是,我有一个方法,它接收chan X作为参数,但是当我传递类型为Y的变量channel时,我得到错误信息"无法将'channel' (类型为chan Y) 用作类型chan X"。
我确保Y确实实现了X的所有方法,但是我不确定如何解决这个问题。非常感谢您对此问题的任何帮助!
谢谢
英文:
I have an interface X and an implementation of X called Y.
The problem is that I have a method which receives chan X as a parameter, but when I pass the variable channel, which is of type Y, I get the error "Cannot use 'channel' (type chan Y) as type chan X".
I have ensured that Y does indeed implement all of X's methods but so I'm unsure of how to solve this problem. Any help on why this is happening would be greatly appreciated!
Thank you
答案1
得分: 2
你不能用这种方式来“解决”这个问题,无论X
和Y
之间的关系如何,chan Y
都不能替代chan X
。
你需要重新修改你的代码,以便在一个函数要求你提供一个chan X
时,你给它一个chan X
。
如果X
是一个接口,并且Y
满足该接口,你可以通过chan X
发送指向Y
的指针,但这并不意味着chan Y
可以作为chan X
使用。这样做将完全违反func(chan X)
的约定。想象一下,如果这个函数接受一个chan X
,却可以接收一个chan Y
。现在,函数内部希望能够通过同一个通道发送一个实现了X
接口的Z
,但由于你给它了错误的通道类型,它无法实现这一点。
英文:
You can't "solve" this problem in that way, a chan Y
cannot be used in place of a chan X
, regardless of the relationship between X
and Y
.
You need to rework your code so that, if a function requires you to give it a chan X
, you're giving it a chan X
.
If X
is an interface, and Y
fulfills that interface, you can send pointers to Y
over a chan X
, but that doesn't make a chan Y
usable as a chan X
. Doing so would completely break the contract of a func(chan X)
. Imagine if that function, accepting a chan X
, could receive a chan Y
. Now internally the function expects to be able to send a Z
, which also implements the X
interface, over that same channel, but can't, because instead of holding the chan X
it requires, you've given it the wrong channel type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论