dongshai8330
2017-08-26 21:36
浏览 7
已采纳

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

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.

图片转代码服务由CSDN问答提供 功能建议

在一个包装中,我有这个:

 包装pkg1  
 
type SomeFuncType函数(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:错误:初始化中的类型不兼容(不能将mypackage.MyFuncType类型用作pkg1.SomeFuncType类型)
 <  / code>  
 
 

如何解决? 这些函数类型定义具有完全相同签名的函数。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyu4822 2017-08-26 21:41
    已采纳

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

    pkg1.PkgApiCall(SomeFuncType(x))
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题