如何将具有相同签名的函数类型进行转换?

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

How can I convert function types with the same signature?

问题

在一个包中,我有以下代码:

package pkg1

type SomeFuncType func(a interface{}, b interface{}) int

func PkgApiCall(x SomeFuncType) {
   ...
}

在使用这个包的代码中,我有以下代码:

type MyFuncType func(a interface{}, b interface{}) int

现在我想调用pkg1.PkgApiCall(),但是要使用MyFuncType类型的变量作为参数:

package mypackage

func doingSomeThing(x MyFuncType) {
  pkg1.PkgApiCall(x)
}

但是它无法编译通过,我得到了以下错误:

./src1.go:97:7: error: incompatible type in initialization (cannot use type mypackage.MyFuncType as type pkg1.SomeFuncType)

我该如何解决这个问题?这些函数类型定义了完全相同的函数签名。

英文:

In a package, I have this:

package pkg1

type SomeFuncType func (a interface{}, b interface{}) int

func PkgApiCall (x SomeFuncType) {
   ...
}

In my code using this package, I have some very similar:

type MyFuncType func (a interface{}, b interface{}) int

Now I want to call pkg1.PkgApiCall(), but with a variable of MyFuncType as argument:

package mypackage

func doingSomeThing(x MyFuncType) {
  pkg1.PkgApiCall(x)
}

It doesn't compile. I get the error

./src1.go:97:7: error: incompatible type in initialization (cannot use type mypackage.MyFuncType as type pkg1.SomeFuncType)

How could I get over this? These function types define functions with exactly the same signature.

答案1

得分: 3

通常的类型转换对于函数类型和非函数类型同样适用:

pkg1.PkgApiCall(SomeFuncType(x))
英文:

The usual type conversions work for function types just as well as they work for non-function types:

pkg1.PkgApiCall(SomeFuncType(x))

huangapple
  • 本文由 发表于 2017年8月27日 05:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/45899868.html
匿名

发表评论

匿名网友

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

确定