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

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

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

报告相同问题?

悬赏问题

  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签)
  • ¥50 sft下载大文阻塞卡死
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具