22

I have a data structure like this demo.

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

func main(){
   per1 := Person{name:"niki",family:&Familys{first:"yam",last:"bari"}}
   Check(per1)
}

and the code:

var validate *validator.Validate
func Check(data interface{}) {
    var v = reflect.ValueOf(data)

    if v.Kind() == reflect.Struct {
        fmt.Println("was a struct")
        v = v.FieldByName("family").FieldByName("last")
        fmt.Println(v)
    }
}

when i do not use point for Family , it back "bari" and it is ok.But with point , there is this error .

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

I searched a lot but i can not find answer can help.

elham anari
  • 518
  • 2
  • 8
  • 22
  • I searched and and found https://stackoverflow.com/questions/22085485/reflect-thinks-struct-value-is-also-a-ptr and https://stackoverflow.com/questions/24537525/reflect-value-fieldbyname-causing-panic - it looks the same doesn't it? Do those help you solve your problem – kabanus Apr 30 '18 at 10:32
  • I check them but when i use Elem() , there is another error and my per1 structure is correct .@kabanus – elham anari Apr 30 '18 at 10:36

1 Answers1

30

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

Zak
  • 5,515
  • 21
  • 33