gpt4 book ai didi

reflection - 如何反射(reflect)Golang中对象的动态方法名

转载 作者:数据小太阳 更新时间:2023-10-29 03:35:40 27 4
gpt4 key购买 nike

例子

router.Get(path, handler) // works fine

methodStr = "Get"
router.methodStr(path, handler) // error

funcs := map[string]func(){"methodStr": "Get"}
router.funcs["methodStr"](path, handler) // error

reflect.ValueOf(router).MethodByName("Get").Call([]reflect.Value{}) // error

我正在获取字符串形式的方法名称。如何使用字符串名称调用路由器对象方法

最佳答案

您遇到的前两个错误不是有效的 Go,因此我不确定您对它们的期望是什么。最后一个带有 reflect 的例子没有任何需要 2 的函数的参数,这会导致 panic。添加 2 个参数效果很好:

http://play.golang.org/p/mSziWdW0hn

args := []reflect.Value{
reflect.ValueOf("path"),
reflect.ValueOf("handler"),
}
reflect.ValueOf(router).MethodByName("Get").Call(args)

关于reflection - 如何反射(reflect)Golang中对象的动态方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35069528/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com