【发布时间】:2021-09-12 06:29:40
【问题描述】:
我正在尝试使用反射对数组的每个元素进行动态函数调用:
var EsPersonList []EsEntry
func (this *EsEntry) FullName() string {
return this.Wholename
}
func createStr(d interface{}) {
items := reflect.ValueOf(d)
if items.Kind() == reflect.Slice {
for i := 0; i < items.Len(); i++ {
item := items.Index(i)
if item.Kind() == reflect.Struct {
v := reflect.ValueOf(&item)
return_values := v.MethodByName("FullName").Call([]reflect.Value{})
fmt.Println(return_values)
}
}
}
}
createStr(EsPersonList)
我得到的是一个看起来像这样的恐慌:
panic: reflect: call of reflect.Value.Call on zero Value
https://play.golang.org/p/vK2hUfVcMwr
我该如何解决这个问题?
【问题讨论】:
-
你必须在
item上打电话给MethodByName,而不是v -
return_values := item.MethodByName("FullName").Call([]reflect.Value{}) 不工作。同样的错误
-
item是reflect.Value。&item是*reflect.Value。reflect.ValueOf(&item)是指向反射的指针的反射,而不是你想要的。 -
play.golang.org/p/l4wIXQ1Vyyb 使用
item.Addr()而不是reflect.ValueOf(&item)。
标签: go reflection