英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论