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

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

报告相同问题?

悬赏问题

  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码