亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何調用反射得到的閉包函數?

如何調用反射得到的閉包函數?

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 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號