2018-10-21 10:51
浏览 375


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:

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

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

import“ fmt” 
type fancyFunc func(a,b,c int)int 
 \  nfunc doFancyStuff(f FancyFunc)int {
做一些特殊的事情return 42 
func main(){
 f1:= func(  a,b,c int)int {return a + b + c} 
 f2:= fancyFunc {return a * b * c} 
 /  /最终,它们的用法如下:
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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

    解决 无用
    打赏 举报

相关推荐 更多相似问题