dimanche 23 septembre 2018

Is is possible to convert a struct to a type passed as a parameter in Go?

Is there a way to convert an object to a type dynamically, at runtime?

I'm aware of the syntax of type assertion, object.(Type), but I want to use this where Type is unknown at compile time and is passed to the function that does the assertion as a parameter.

My scenario is I have a few different types with different structures defined; let's call them Type1 and Type2. After I define an object of a specific type (Type1 or Type2), it's saved in a DB, where its type is cleared, and the raw data is all that's left. I can read the raw data and save it in an interface{}.

Now, I need to read specific properties from the object based on its type, so I'm trying to find a way to convert the raw interface to the type I need at runtime.





Aucun commentaire:

Enregistrer un commentaire