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

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

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

问题

我正在尝试使用反射来对数组的每个元素进行动态函数调用:

  1. var EsPersonList []EsEntry
  2. func (this *EsEntry) FullName() string {
  3. return this.Wholename
  4. }
  5. func createStr(d interface{}) {
  6. items := reflect.ValueOf(d)
  7. if items.Kind() == reflect.Slice {
  8. for i := 0; i < items.Len(); i++ {
  9. item := items.Index(i)
  10. if item.Kind() == reflect.Struct {
  11. v := reflect.ValueOf(&item)
  12. return_values := v.MethodByName("FullName").Call([]reflect.Value{})
  13. fmt.Println(return_values)
  14. }
  15. }
  16. }
  17. }
  18. 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:

  1. var EsPersonList []EsEntry
  2. func (this *EsEntry) FullName() string {
  3. return this.Wholename
  4. }
  5. func createStr(d interface{}) {
  6. items := reflect.ValueOf(d)
  7. if items.Kind() == reflect.Slice {
  8. for i := 0; i &lt; items.Len(); i++ {
  9. item := items.Index(i)
  10. if item.Kind() == reflect.Struct {
  11. v := reflect.ValueOf(&amp;item)
  12. return_values := v.MethodByName(&quot;FullName&quot;).Call([]reflect.Value{})
  13. fmt.Println(return_values)
  14. }
  15. }
  16. }
  17. }
  18. 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:

确定