dstbp22002 2018-04-30 10:29
浏览 809
已采纳

反射:在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)
}

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.

  • 写回答

1条回答 默认 最新

  • doutui4649 2018-04-30 10:36
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改