Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading