本文介绍了反射:在ptr值上调用reflect.Value.FieldByName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似此演示的数据结构.

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)
}

和代码:

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)
    }
}

当我不为家庭使用Point时,它会返回"bari"并且可以.但是对于point来说,会出现此错误.

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

我搜索了很多,但找不到答案可以帮忙.

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

推荐答案

您已经注意到,家庭 *家庭.正如错误所言,您不能在 reflect.Value 上调用 .FieldByName(...),其中该值是一个指针.

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.

相反,您需要间接指针,以获取其指向的值,然后在其上调用 .FieldByName(...).

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")

请参阅间接文档: https://golang.org/pkg/reflect/#Indirect

这篇关于反射:在ptr值上调用reflect.Value.FieldByName的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 23:58