vendredi 6 septembre 2019

Creating type by reflection and passing by reference compiles but does not work

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.





Aucun commentaire:

Enregistrer un commentaire