英文:
Call MethodByName in array of struct: panic: reflect: call of reflect.Value.Call on zero Value
问题
我正在尝试使用反射来对数组的每个元素进行动态函数调用:
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
你可以如何修复这个问题?
英文:
I am trying to use reflection to make a dynamic function call of each element of an array:
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)
I get is a panic that looks like this:
panic: reflect: call of reflect.Value.Call on zero Value
https://play.golang.org/p/vK2hUfVcMwr
How can I fix this?
答案1
得分: 0
根据 mkopriva 的评论 中所述,使用 item.Addr() 来获取字段的地址,而不是 reflect.ValueOf(&item)。后者获取的是反射值的反射值。方法调用失败是因为 reflect.Value 没有 FullName 方法。
英文:
As stated in the comment by mkopriva, use item.Addr() to get address of the field, not reflect.ValueOf(&item).  The latter gets the reflect value of a reflect value.  The method call fails because reflect.Value does not have the method FullName.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论