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

如何在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条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥30 关于#c++#的问题:用C++编程实现主存-Cache地址映射(附运行成功截图+注释)
      • ¥25 接口/特征方法的异常错误返回如何判断是否需要设计
      • ¥40 代码+预测分析,文件私信发哦(价格可商量)
      • ¥15 GAMES101 HW1 无法定义
      • ¥15 pycharm不管允许什么代码都出错,都会出现下面的情况。
      • ¥15 boost::integrate的用法
      • ¥20 51单片机输出pwm时无法调节频率,如何解决?
      • ¥15 DSP28335 AD采集正弦波
      • ¥50 pwwinauto调式修改
      • ¥30 关于#单片机#的问题:单片机基于51单片机开发计时器,使其实现以下功能:(1)开发板上四个独立按键分别控制计时器的启停、计时器的复位(按下计时值归零)、计时位切换、计时时间的递增