Go中函数变量的类型

jos*_*hlf 2 types function-pointers go higher-order-functions

我想写一个函数,它接受任何类型函数的指针.我可以:

func myFunc(f interface{})
Run Code Online (Sandbox Code Playgroud)

...但这将允许非功能值.有什么办法可以将类型限制为任何函数吗?

Luk*_*uke 5

假设你的字面意思是任何函数,你可以做一个类型切换(这是特定的):

switch v.(type) {
case func() int:
case func() string:
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用reflect包来确定类型:

if reflect.TypeOf(v).Kind() != reflect.Func {
    // error here
}
Run Code Online (Sandbox Code Playgroud)

这是一个运行时解决方案.除此之外,你无能为力.关于这一点的缺点是编译器不会阻止某人传递非函数值.

就个人而言,我会避免这样做,我希望有一个特定的func原型,如:

func myFunc(f func() string)
Run Code Online (Sandbox Code Playgroud)

有了这个,当编译器知道类型是什么时,你就不太可能出错.