无法将 chan 实现传递给需要 chan 接口的方法。

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

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

你不能用这种方式来“解决”这个问题,无论XY之间的关系如何,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.

huangapple
  • 本文由 发表于 2022年3月15日 04:05:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/71473633.html
匿名

发表评论

匿名网友

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

确定