【问题标题】:Set a pointer to a field using reflection使用反射设置指向字段的指针
【发布时间】:2014-07-22 14:53:57
【问题描述】:

我有以下结构,并且需要一些字段可以为空,所以我使用指针,主要是处理 sql 空值

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

所以当我执行以下操作时,我可以看到 json 结果可以包含我想要的值类型的空值

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

但是当我尝试使用反射来完成这一切时

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

我从反射部分得到的是以下错误

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

我做错了什么?

这是一个 GoPlay http://play.golang.org/p/0xt45uHoUn

【问题讨论】:

    标签: go


    【解决方案1】:

    reflect.Value.Set 仅接受 reflect.Value 作为参数。在您的 stringValue 上使用 reflect.ValueOf

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

    游乐场:http://play.golang.org/p/DNxsbCsKZA.

    【讨论】:

      猜你喜欢
      • 2018-03-03
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 2019-12-19
      • 2021-01-20
      • 2012-07-02
      • 1970-01-01
      相关资源
      最近更新 更多