使用反射设置一个字段的指针。

huangapple go评论112阅读模式
英文:

Set a pointer to a field using reflection

问题

我有以下的结构体,并且需要一些字段可以为null,所以我使用了指针,主要是为了处理SQL的null值。

  1. type Chicken struct {
  2. Id int //不可为null
  3. Name *string //可以为null
  4. AvgMonthlyEggs *float32 //可以为null
  5. BirthDate *time.Time //可以为null
  6. }

当我执行以下操作时,我可以看到JSON结果中的值类型可以为null,这正是我想要的。

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

但是当我尝试使用反射来完成所有操作时:

  1. var chickenPtr *Chicken
  2. itemTyp := reflect.TypeOf(chickenPtr).Elem()
  3. item := reflect.New(itemTyp)
  4. item.Elem().FieldByName("Id").SetInt(1)
  5. //问题出在这里,不确定如何将指针设置给字段
  6. item.Elem().FieldByName("Name").Set(&stringValue) //这一行引发了错误
  7. itemJson, _ := json.Marshal(item.Interface())
  8. fmt.Println(string(itemJson))

从反射部分得到的错误如下:

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

我做错了什么?

英文:

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

  1. type Chicken struct{
  2. Id int //Not nullable
  3. Name *string //can be null
  4. AvgMonthlyEggs *float32 //can be null
  5. BirthDate *time.Time //can be null
  6. }

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

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

but when i try to do it all using reflection

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

what i get from the reflection part is the following error

  1. 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

得分: 3

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

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

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

英文:

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

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

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

huangapple
  • 本文由 发表于 2014年7月22日 22:53:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/24890732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定