FPGA
FPGA

Reputation: 3875

Set a pointer to a field using reflection

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

Upvotes: 0

Views: 2121

Answers (1)

Ainar-G
Ainar-G

Reputation: 36259

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.

Upvotes: 3

Related Questions