Function type returning interface does not match function returning concrete at compile time

Hey guys, I am pretty sure this must have been discussed here, but it’s difficult for me to properly formulate a headline resp. searching for an existing entry. Hope for your forgiveness.

So I got a function type and it defines some factory function.
To have some adapter pattern I want it to return an interface type.

So the idea is:
For each adapter implementation I just have some factory function that returns a type
implementing the required Adapter interface.

Unfortunately using the concrete factory function only work if I wrap them in an anonymous function.

On the one hand this works, ok.
On the other hand, I do not understand why it works or I don’t understand why my naive attempt to directly use the factory functions does not work.

I put an example here, showing the working and not working version next to each other.
https://play.golang.org/p/QMDzs7bKHNQ

Is this about strictness to enforce well readable code or is this details missing in compiler implementation? To me the code I have to produce unnecessarily verbose.

Bonus: plus points given for the one who tells a more proper topic name.

1 Like

Just like Go doesn’t have any concept of inheritance, it also has no concept of covariance or contravariance. Your useF function accepts an F as its parameter. F is defined as func() I, but NewC is of type func() C which is not the same type, even though C implements I. Functions are concrete types, so it’s just like attempting to pass an int32 into a function that accepts an int64: Even though you can think of int32 as a strict subset of int64, it’s a different type, so the compiler complains.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.