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!
Aucun commentaire:
Enregistrer un commentaire