reflect: call of reflect.Value.FieldByName on ptr Value

前端 未结 1 1134
小鲜肉
小鲜肉 2021-02-20 13:53

I have a data structure like this demo.

type Family struct {
   first string
   last string
}
type Person struct {
   name string
   family *Family
}

func main(         


        
相关标签:
1条回答
  • 2021-02-20 14:04

    As you've noted, family is *Family. And as the error says, you cannot call .FieldByName(...) on a reflect.Value where that value is a pointer.

    Instead you need to indirect the pointer, to get the value that it points to, and call .FieldByName(...) on that.

    familyPtr := v.FieldByName("family")
    v = reflect.Indirect(familyPtr).FieldByName("last")
    

    See docs on indirect: https://golang.org/pkg/reflect/#Indirect

    0 讨论(0)
提交回复
热议问题