drdr123456 2014-07-22 14:53
浏览 55
已采纳

使用反射设置指向字段的指针

i have the following struct, and need some of the fields to be nulluble so i use pointers, mainly to handle sql nulls

type Chicken struct{
    Id                int         //Not nullable
    Name              *string     //can be null
    AvgMonthlyEggs    *float32    //can be null
    BirthDate         *time.Time  //can be null
}

so when i do the following i can see that the json result can have nulls for value types which is what i want

stringValue:="xx"
chicken := &Chicken{1,&stringValue,nil,nil}
chickenJson,_ := json.Marshal(&chicken)
fmt.Println(string(chickenJson))

but when i try to do it all using reflection

    var chickenPtr *Chicken
    itemTyp := reflect.TypeOf(chickenPtr).Elem()
    item  := reflect.New(itemTyp)
    item.Elem().FieldByName("Id").SetInt(1)
    //the problem is here not sure how to set the pointer to the field
    item.Elem().FieldByName("Name").Set(&stringValue) //Error caused by this line
    itemJson,_ := json.Marshal(item.Interface())
    fmt.Println(string(itemJson))

what i get from the reflection part is the following error

cannot use &stringValue (type *string) as type reflect.Value in argument to item.Elem().FieldByName("Name").Set

what am i doing wrong?

here is a GoPlay http://play.golang.org/p/0xt45uHoUn

  • 写回答

1条回答 默认 最新

  • douzhi3105 2014-07-22 15:06
    关注

    reflect.Value.Set only accepts reflect.Value as an argument. Use reflect.ValueOf on your stringValue:

    item.Elem().FieldByName("Name").Set(reflect.ValueOf(&stringValue))
    

    Playground: http://play.golang.org/p/DNxsbCsKZA.

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

报告相同问题?

悬赏问题

  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建