doucheng5209 2014-12-15 13:42
浏览 42
已采纳

将不同的结构传递给函数(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).

  • 写回答

1条回答 默认 最新

  • dsgoj7457 2014-12-15 15:58
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1