Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify null pointer field in struct through reflection in Go

I'm trying to modify the indirect value of the null pointer field "MyField" through a reflection loop. I'm getting a panic: reflect: call of reflect.Value.Set on zero Value.

Any ideas on how to do it?

https://play.golang.org/p/IJvA_J_cD60

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
    MyField *string
}

func main() {
    s := MyStruct{}

    v := reflect.ValueOf(s)

    for i := 0; i < v.NumField(); i++ {
        valueField := v.Field(i)
        fieldName := v.Type().Field(i).Name
        if fieldName == "MyField" && valueField.Kind() == reflect.Ptr {
            valueField.Elem().Set(reflect.ValueOf("some changed name"))
            fmt.Printf("the elem after change: %v\n", valueField.Elem())
        }

    }
    fmt.Print(*s.MyField)
}

Thanks a lot!

like image 470
pmrs Avatar asked Sep 17 '25 23:09

pmrs


1 Answers

There are two issues with the program.

The field cannot be set because v is not an addressable value. To get an addressable value, create a reflect.Value from a pointer to s:

s := MyStruct{}
v := reflect.ValueOf(&s).Elem()

The program attempts to set a value through a nil pointer. The reflect code is identical to *s.MyField = "some changed name". This statement will panic if MyField is nil as it is in the question. To fix this, set a pointer into the field:

t := "some changed name"
valueField.Set(reflect.ValueOf(&t))

Run it on the Playground


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!