pointers – Creating type by reflection and passing by reference compiles but does not work-ThrowExceptions

Exception or error:

When I dynamically create a pointer to a type and then pass it in to an unmarshalling function, it seems to be written correctly, in theory:

x := reflect.New(structType)
decode(x)

However, when you print x, it looks like the zero value of the type. The type is definitely correct and expected.

On the other hand, when I create the type and pass a pointer to it, directly, it works fine:

directoryEntry := DirectoryEntry{}
decode(&directoryEntry)

The contents are set correctly by decode() and, when printed, are correct.

So, it seems like I must be passing a value of the type to decode() and not a reference?

Can someone point out what I must be missing? A number of Google queries didn’t help, and it seems like I must be missing something small.

How to solve:

reflect.New() returns you a pointer to a value of the passed type, but the returned pointer is wrapped in a reflect.Value struct!

Use Value.Interface() to “unwrap” it, and have a pointer as an interface{} which you can pass to decode():

x := reflect.New(structType)
p := x.Interface()
decode(p)

When you print a reflect.Value, you often won’t see a difference, because the reflect.Value type is treated special; quoting from Value.String():

The fmt package treats Values specially. It does not call their String method implicitly but instead prints the concrete values they hold.

Leave a Reply

Your email address will not be published. Required fields are marked *