doumu5662 2015-08-12 12:20
浏览 20
已采纳

调用函数,无论其参数类型如何

Suppose I have a function which resides in the fn property of the following Method struct:

type Method struct {
  fn interface{}
}

var inst = &Method{func(a, b int) int {
  return a + b
}}

Now, I want to invoke this function with two arguments without explicitly casting it to func(int, int) int like so

a := 5
b := 6
fmt.Println(inst.fn(a, b))

How can I achieve this? Is there some generic solution for this?

  • 写回答

1条回答 默认 最新

  • duanjiao2978 2015-08-12 12:27
    关注

    The only way I know is by using reflect.Value.Call:

    type Method struct {
        fn interface{}
    }
    
    func (m Method) Call(args ...interface{}) {
        vs := make([]reflect.Value, len(args))
        for i := range args {
            vs[i] = reflect.ValueOf(args[i])
        }
        v := reflect.ValueOf(m.fn)
        v.Call(vs)
    }
    
    func main() {
        f := func(a, b int) {
            fmt.Println(a + b)
        }
        m := Method{f}
        m.Call(2, 3)
    }
    

    Playground: http://play.golang.org/p/JNtj2EMpu7.

    Note: this will panic if fn is not a function or if the number or types of arguments are wrong. If you don't want that, you need to recheck all those conditions yourself.

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

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起