为了账号安全,请及时绑定邮箱和手机立即绑定

如何调用反射得到的闭包函数?

如何调用反射得到的闭包函数?

Go
三国纷争 2023-06-05 16:55:28
我正在尝试使用 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 指针(调试器中值地址上设置的标志为 147,归结为可寻址)。欢迎任何关于正在发生的事情的建议,或者如果可能的话。操场链接: https: //play.golang.org/p/0EPSCXKYOp0package mainimport (    "fmt"    "reflect"    "unsafe")// Typed Struct to hold the initialized jobs and group Filter function typestype GenericCollection struct {    jobs []*Generic}type Generic func (target int) intfunc main() {    jjf := &GenericCollection{jobs: []*Generic{}}    jjf.JobFactoryCl("Type", 20)}// Returns job function with closure on jobtypefunc (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 factoryfunc (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        }
查看完整描述

1 回答

?
Cats萌萌

TA贡献1805条经验 获得超9个赞

键入断言方法值到具有适当签名的函数。调用那个函数。

问题的第一个例子:

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

}

在操场上运行

问题的第二个例子:


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

}

在操场上运行


查看完整回答
反对 回复 2023-06-05
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信