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

如何在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))
}
  • 写回答

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).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?