如何调用通过反射获得的闭包函数?

时间:2019-01-31 22:00:59

标签: go reflection closures

我正在尝试使用Go的反射库,但遇到一个我无法弄清楚的问题:如何通过反射调用闭包函数返回一个函数?基本上可以有以下顺序吗?

func (f someType) closureFn(i int) int {
  return func (x int) int {
     return x+i
  }
}
...

fn := reflect.ValueOf(&f).MethodByName("closureFn")
val := append([]reflect.Value{}, reflect.ValueOf(99))
fn0 := fn.Call(val)[0]
fn0p := (*func(int) int)(unsafe.Pointer(&f0))
m := (*fn0p)(100)

哪个应该使m等于199?

下面是演示此问题的简化代码。对“虚拟”匿名函数的调用可以正常工作,对闭包的反射调用也可以。但是,使用nil指针尝试调用闭包返回失败(在调试器中,Value的地址上设置的标志为147,该标志变为可寻址的)。 欢迎就正在发生的事情或是否有可能提出任何建议。

链接到游乐场:https://play.golang.org/p/0EPSCXKYOp0

package main

import (
    "fmt"
    "reflect"
    "unsafe"
)

// Typed Struct to hold the initialized jobs and group Filter function types
type GenericCollection struct {
    jobs []*Generic
}

type Generic func (target int) int

func main() {
    jjf := &GenericCollection{jobs: []*Generic{}}
    jjf.JobFactoryCl("Type", 20)
}


// Returns job function with closure on jobtype
func (f GenericCollection) Job_by_Type_Cl(jobtype int) (func(int) int) {
    fmt.Println("Job type is initialized to:", jobtype)

    // Function to return
    fc := func(target int) int {
        fmt.Println("inside JobType function")
            return target*jobtype
    }
    return fc
}

// Function factory
func (f GenericCollection) JobFactoryCl(name string, jobtype int) (jf func(int) int) {

    fn := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl")
    val := append([]reflect.Value{}, reflect.ValueOf(jobtype))
    if fn != reflect.ValueOf(nil) {

        // Reflected function -- CALLING IT FAILS
        f0 := fn.Call(val)[0]
        f0p := unsafe.Pointer(&f0)

        //Local dummy anonymous function - CALLING IS OK
        f1 := func(i int) int {
            fmt.Println("Dummy got", i)
            return i+3
        }
        f1p := unsafe.Pointer(&f1)

        // Named function

        pointers := []unsafe.Pointer{f0p, f1p}

        // Try running f1 - OK
        f1r := (*func(int) int)(pointers[1])
        fmt.Println((*f1r)(1))
        (*f1r)(1)

        // Try calling f0 - FAILS. nil pointer dereference
        f0r := (*func(int) int)(pointers[0])
        fmt.Println((*f0r)(1))

        jf = *f0r
    }
    return jf
}

1 个答案:

答案 0 :(得分:3)

Type assert method value转换为具有适当签名的函数。调用该函数。

第一个问题示例:

type F struct{}

func (f F) ClosureFn(i int) func(int) int {
    return func(x int) int {
        return x + i
    }
}

func main() {
    var f F
    fn := reflect.ValueOf(&f).MethodByName("ClosureFn")

    fn0 := fn.Call([]reflect.Value{reflect.ValueOf(99)})[0].Interface().(func(int) int)
    fmt.Println(fn0(100))

    // It's also possible to type assert directly 
    // the function type that returns the closure.
    fn1 := fn.Interface().(func(int) func(int) int)
    fmt.Println(fn1(99)(100))
}

Run it on the Playground

问题的第二个例子:

func (f GenericCollection) JobFactoryCl(name string, jobtype int) func(int) int {
    jf := reflect.ValueOf(&f).MethodByName("Job_by_" + name + "_Cl").Interface().(func(int) func(int) int)
    return jf(jobtype)
}

func main() {
   jjf := &GenericCollection{jobs: []*Generic{}}
   jf := jjf.JobFactoryCl("Type", 20)
   fmt.Println(jf(10))
}

Run it on the Playground