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
", valueField.Elem())
}
}
fmt.Print(*s.MyField)
}
Thanks a lot!
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))