samedi 19 décembre 2015

How can I pass an interfaec{} instance to a function that expects a struct pointer?

The GORM library has us perform queries by passing pointers to structs that are mapped to database tables, for instance: db.First(&user). In doing so, the First function fills all of user's fields with the data it fetches from the underlying database.

Now suppose we have a function that receives an interface{} parameter that is guaranteed to correspond to a valid ORM struct, for instance:

func (crud DbCRUD) Read(r interface{}) error {
    return crud.db.First(r).Error
}

This particular function fails with a unsupported destination, should be slice or struct message, coming from gorm.Query. The error seems to relate to the fact that gorm.Query expects a slice or a struct, and is instead receiving an interface{}.

My question is therefore the following: how can I obtain a pointer to the struct underlying r in the above function, such that it can be passed to gorm.DB.First?

Intuitively, it would seem that the reflect package is involved, but I'm having trouble stringing the pieces together.





Aucun commentaire:

Enregistrer un commentaire