Reputation: 9109
Consider such function that accepts function as argument:
func f(arg func(I)){}
where I
is interface.
Is there any way to pass into above function an argument of signature func(*T)
where T
implements I
interface.
Now when I pass it, I have an error:
cannot use (type func(*T)) as type func(I) in argument
Here is playground: https://play.golang.org/p/7vilY4zkEzf
Use case is the following:
I write package that has f(a func(I), b I)
function. Then user will import it as library.
As a next step, user will define a custom type T
that implements I
interface and a custom function with signature func(*T)
. Then user will call library f
function:
f(customFunction, customObject)
In turn, package will receive it and create a goroutine:
go customFunction(customObject)
The reason why goroutines are created "inside" package is that goroutine orchestration should be hold "under the hood".
Upvotes: 2
Views: 726
Reputation: 2736
No, the types need to be exact. Your example is especially broken because I
isn't definitely convertible to *T
, but it also wouldn't work the other way. If you're sure that the type of the I
being passed to your function is *T
, you could create wrapper function and pass that instead.
func wrapper(i I) {
t := i.(*T)
myRealFunc(t)
}
Upvotes: 6