Search code examples
gomgo

Passing different structs to a function (GO)?


I have a function like the following for querying a mongo database:

func findEntry(db, table string, entry *User, finder *bson.M) (err error) {
    c := mongoSession.DB(db).C(table)
    return c.Find(finder).One(entry)
}

I'd like to reuse the function for structs other than "User", by passing in a pointer to any instantiated struct object - just not quite sure of the proper semantics to do this. I think that I should be able to do this by making the 'entry' parameter an interface{} and then I'd need to use reflection to 'cast' it back to the original struct so the One() function call could properly fill in the struct on the call? Is there a 'better' way to accomplish this (please no flaming about lack of generics, I'm just looking for a practical solution using best practices).


Solution

  • Use this function:

    func findEntry(db, table string, entry interface{}, finder bson.M) error {
        c := mongoSession.DB(db).C(table)
        return c.Find(finder).One(entry)
    }
    

    and call it like:

    var user User
    err := findEntry("db", "users", &user, bson.M{"name": "John"})
    

    The type information for user is passed through findEntry to the One method. There's no need for reflection or a "cast" in findEntry.

    Also, use bson.M instead of *bson.M. There's no need to use a pointer here.

    I created an example on the playground to show that the type information is passed through findEntry.