4

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!

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Many thanks! In this case I know the field type. What if I wanted to initialize the field with a Empty/Zero value of the type pointed (i.e. empty string in this case)? Any thoughts on that?
valueField.Set(reflect.New(valueField.Type().Elem()))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.