Call MethodByName in array of struct: panic: reflect: call of reflect.Value.Call on zero Value

huangapple go评论67阅读模式
英文:

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 &lt; items.Len(); i++ {
			item := items.Index(i)
			if item.Kind() == reflect.Struct {
				v := reflect.ValueOf(&amp;item)
				return_values := v.MethodByName(&quot;FullName&quot;).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(&amp;item)。后者获取的是反射值的反射值。方法调用失败是因为 reflect.Value 没有 FullName 方法。

英文:

As stated in the comment by mkopriva, use item.Addr() to get address of the field, not reflect.ValueOf(&amp;item). The latter gets the reflect value of a reflect value. The method call fails because reflect.Value does not have the method FullName.

huangapple
  • 本文由 发表于 2021年6月30日 13:37:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/68188975.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定