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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?