vendredi 29 juillet 2022

Golang reflect get nil pointer underlying type

I would like to know if there is a way to "cast" a nil pointer of a struct into the (empty) struct itself using reflection or anything else.

My method parameters are an empty parent struct as an interface, a field name as a string and the field value as an interface.

The point is to get the real type of the field by going through the parent struct until I find the field matching the given name. I cannot just get the type of the value, because there will be cases where it won't return the correct type (for example a time.Time will be seen as a string).

The method can take any struct as parent, which is why it takes interfaces as parameters.

My problem is that the parent struct that is given is always a empty one (it serves only as a model), with default values. So fields that are pointers to substructs are nil. So to find the field given as parameter, I have to get the underlying substruct instead of the nil pointer to continue the search inside.

I cannot find a way to achieve that, I am not sure if that's even possible.

Any help is welcomed.





Aucun commentaire:

Enregistrer un commentaire