doufang8965
2018-10-21 10:51
浏览 260
已采纳

如何在golang中实例化函数类型?

I would like to instantiate a bunch of functions of the same type without having to duplicate their signature. I already have a function type describing that signature (fancyFunc below) and another function consuming arguments of that kind (doFancyStuff below). How would I make something like this work?

package main

import "fmt"

type fancyFunc func(a,b,c int) int

func doFancyStuff(f FancyFunc) int {
    // Do something special with f
    return 42
}

func main() {
    // This works but is rather tedious:
    f1 := func(a,b,c int) int { return a + b + c }

    // I would like to create them like this:
    f2 := fancyFunc{ return a * b * c }

    // Eventually, they are used like this:
    fmt.Println(doFancyStuff(f1))
    fmt.Println(doFancyStuff(f2))
}

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

我想实例化一堆相同类型的函数,而不必复制其签名。 我已经有一个描述该签名的函数类型(下面的 fancyFunc )和另一个使用该类型参数的函数(下面的 doFancyStuff )。 我该如何做这样的工作?

 包main 
 
import“ fmt” 
 
type fancyFunc func(a,b,c int)int 
 \  nfunc doFancyStuff(f FancyFunc)int {
 //用f 
做一些特殊的事情return 42 
} 
 
func main(){
 //可以,但是很乏味:
 f1:= func(  a,b,c int)int {return a + b + c} 
 
 //我要像这样创建它们:
 f2:= fancyFunc {return a * b * c} 
 
 /  /最终,它们的用法如下:
 fmt.Println(doFancyStuff(f1))
 fmt.Println(doFancyStuff(f2))
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douaoj0994 2018-10-21 11:40
    已采纳

    You can only do it as in the f1 case, or by defining a normal function. there is nothing like the f2 way. In C people do this with macros, but Go doesn't have a preprocessor (there are a few unofficial ones you can use).

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题