![](/img/trans.png)
[英]Aerospike Golang client putObject method gives me panic: reflect: call of reflect.Value.Elem on map Value
[英]Reflection - method call panics with “call of reflect.Value.Elem on struct Value”
这是一个代码片段 -
type Gateway struct {
Svc1 svc1.Interface
Svc2 svc2.Interface
}
func (g *Gateway) GetClient(service string) interface{} {
ps := reflect.ValueOf(g)
s := ps.Elem()
f := s.FieldByName(strings.Title(service))
return f.Interface()
}
func (g *Gateway) Invoke(service string, endpoint string, args...
interface{}) []reflect.Value {
log.Info("Gateway.Invoke " + service + "." + endpoint)
inputs := make([]reflect.Value, len(args))
for i, _ := range args {
inputs[i] = reflect.ValueOf(args[i])
}
client := g.GetClient(service)
return reflect.ValueOf(client).Elem().MethodByName(endpoint).Call(inputs)
}
GetClient("svc1") 工作正常。
但是,当我调用 Invoke("svc1", "endpoint1", someArg) 时,它会恐慌地说 -
reflect: call of reflect.Value.Elem on struct Value
reflect.ValueOf(client).MethodByName(endpoint).Call(inputs) 恐慌说调用零值。
有几个问题:
如果svc1.Interface
不是指针或接口, reflect.Value.Elem()
将恐慌(参见https://golang.org/pkg/reflect/#Value.Elem )
如果Invoke
的endpoint
参数字符串与目标方法的大小写不匹配,它会因零值( invalid reflect.Value
)而恐慌。 请注意,您要调用的方法必须是导出的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.