2019-01-31 22:00
浏览 103


I'm experimenting with using Go's reflection library and have come to an issue I cannot figure out: How does one call on a function returned from calling a closure function via reflection? Is it possible to basically have a sequence of:

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)

Which should get m to equal 199?

The following is the simplified code that demonstrates the issue. The call to the "dummy" anonymous function works ok, as does the reflective call to the closure. However attempts at calling on the closure return fail with a nil pointer (the flag set on the address of the Value in the debugger is 147, which comes down to addressable). Any suggestions on what's going on, or if it's at all possible are welcome.

Link to playground: https://play.golang.org/p/0EPSCXKYOp0

package main

import (

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

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

        jf = *f0r
    return jf
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhuan6336 2019-02-01 01:08

    Type assert the method value to a function with the appropriate signature. Call that function.

    First example from the question:

    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)
        // It's also possible to type assert directly 
        // the function type that returns the closure.
        fn1 := fn.Interface().(func(int) func(int) int)

    Run it on the Playground

    Second example from the question:

    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)

    Run it on the Playground

    解决 无用
    打赏 举报

相关推荐 更多相似问题