这是Calling a function with Go Reflect之后的内容。
为了简化这个问题,我想尽办法,对一些值进行了硬编码,并希望〜并没有使过程变得不清楚。我在底部附近的代码“ method.Call(env)”上遇到错误。
理想情况下,我想做的是尽量减少反射的使用,这与ThunderCat在第一个问题上所做的类似:
method := miType.Method(i).Func.Interface().(func(core.ModuleInfo) core.ModuleInfo)
,但是如果不可能,那么最简单的方法就可以了。抱歉,如果这似乎是一个基本问题,我是Go的新手。
我得到的错误是:
cannot use env (type Environment) as type []reflect.Value in argument to method.Call
这是因为我想像上一个问题一样对具有正确签名的函数断言,但是经过一番尝试之后,我还没有完全理解它。
简化代码:
package main
import (
"flag"
"fmt"
"reflect"
)
type CommandLineFlags struct {
Debug *bool
}
type Environment struct {
CLF CommandLineFlags
}
type ModuleInfo struct {
Initialize bool // Flag: True of module has Initialization function and it should be called. Default: false
Module string // Name of the module. No need to hard code, will be set during initialization.
}
type ModuleInit struct{}
func main() {
var env Environment
env.CLF.Debug = flag.Bool("dbg", false, "Enables Debug Messages")
flag.Parse()
modules := make([]ModuleInfo, 1)
modules[0].Initialize = true
modules[0].Module = "logger"
miValue := reflect.ValueOf(ModuleInit{})
// miType := reflect.TypeOf(ModuleInit{})
for _, m := range modules {
if m.Initialize {
funcName := m.Module + "Init"
method := miValue.MethodByName(funcName)
fmt.Println(funcName)
// Would like to do something like this
// ...Func.Interface().(func(core.ModuleInit) core.ModuleInit)
// like is done with the referenced quesiton above so as to minimize the use of reflect calls.
method.Call(env)
}
}
}
func (mi ModuleInit) LoggerInit(env *Environment) {
var debugEnabled = *env.CLF.Debug
// ...and more stuff.
}
答案 0 :(得分:2)
该方法的类型为func(*Environment)
。 Assert to that type并致电:
modules := make([]ModuleInfo, 1)
modules[0].Initialize = true
modules[0].Module = "Logger"
miValue := reflect.ValueOf(ModuleInit{})
for _, m := range modules {
if m.Initialize {
funcName := m.Module + "Init"
method := miValue.MethodByName(funcName).Interface().(func(*Environment))
method(&env)
}
}
(已解决两个问题:模块应为"Logger"
,而不是"logger"
,方法采用*Environment
,而不是Environment
。)
如果找不到该方法或类型不正确,则上面的代码将出现恐慌。这是带有检查功能的代码,可以防止出现紧急情况:
modules := make([]ModuleInfo, 1)
modules[0].Initialize = true
modules[0].Module = "Logger"
miValue := reflect.ValueOf(ModuleInit{})
for _, m := range modules {
if m.Initialize {
funcName := m.Module + "Init"
method := miValue.MethodByName(funcName)
if !method.IsValid() {
fmt.Printf("method %s not found", funcName)
continue
}
fn, ok := method.Interface().(func(*Environment))
if !ok {
fmt.Println("method is not func(*Environment)")
continue
}
fn(&env)
}
}
答案 1 :(得分:1)
OP代码中有几个错误
这是固定版本(https://play.golang.org/p/FIEc6bTvGWJ)。
package main
import (
"flag"
"fmt"
"log"
"reflect"
"strings"
)
type CommandLineFlags struct {
Debug *bool
}
type Environment struct {
CLF CommandLineFlags
}
type ModuleInfo struct {
Initialize bool // Flag: True of module has Initialization function and it should be called. Default: false
Module string // Name of the module. No need to hard code, will be set during initialization.
}
type ModuleInit struct{}
func main() {
var env Environment
env.CLF.Debug = flag.Bool("dbg", false, "Enables Debug Messages")
flag.Parse()
modules := make([]ModuleInfo, 1)
modules[0].Initialize = true
modules[0].Module = "logger"
miValue := reflect.ValueOf(ModuleInit{})
// miType := reflect.TypeOf(ModuleInit{})
for _, m := range modules {
if m.Initialize {
funcName := strings.Title(m.Module) + "Init"
method := miValue.MethodByName(funcName)
log.Printf("%#v %v\n", method, funcName)
if !method.IsValid() || method.IsNil() {
break
}
fmt.Println(funcName)
// Would like to do something like this
// ...Func.Interface().(func(core.ModuleInit) core.ModuleInit)
// like is done with the referenced quesiton above so as to minimize the use of reflect calls.
out := method.Call([]reflect.Value{reflect.ValueOf(env)})
fmt.Println(out) // A bunch of relfect.Values.
}
}
}
func (mi ModuleInit) LoggerInit(env Environment) {
var debugEnabled = *env.CLF.Debug
// ...and more stuff.
log.Println("LoggerInit ", debugEnabled)
}
答案 2 :(得分:0)
问题在于,传递给reflect.Value.Call
的参数本身必须为reflect.Value
类型。查看来自https://golang.org/pkg/reflect/#Value.Call
func (v Value) Call(in []Value) []Value
答案 3 :(得分:0)
您必须将env
变量包装在[]reflect.Value
中,因为reflect.Value.Call
需要一片reflect.Value
。
args := []reflect.Value{reflect.ValueOf(&env),}
method.Call(args)
此外,您的代码中还有一些错别字:
modules[0].Module = "Logger"