Cannot pass chan implementation to method requiring chan interface


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


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.

Answered By – meagar

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.