英文:
Converting Method to generic way, finding with mgo
问题
我正在尝试使getObj()函数更通用,可以适用于任何类型,而不仅仅是像我的代码中那样的User类型。
我在考虑返回一个接口而不是定义的结构体,但是我无法将这个想法融入到我的代码中,请问有人可以帮我吗?
谢谢提前帮助。
type User struct {
FirstName string `bson:"first_name"`
LastName string `bson:"last_name"`
}
type Mbase struct {
coll *mgo.Collection
sess *mgo.Session
}
func (b *Mbase) getObj(attr string, val string) (res *User, err error) {
err = b.coll.Find(bson.M{attr: val}).One(&res)
if err != nil {
return
}
err = nil
return
}
英文:
I'm trying to get getObj() function will be more general and could
work with any type, not only User like in my code.
I was thinking in return a interface instead a defined struct, but I can't fit this
idea to my code, please could someone give me a hand with this?
<br>Thanks in advance
type User struct {
FirstName string `bson:"first_name"`
LastName string `bson:"last_name"`
}
type Mbase struct {
coll *mgo.Collection
sess *mgo.Session
}
func (b *Mbase) getObj(attr string, val string) (res *User, err error) {
err = b.coll.Find(bson.M{attr: val}).One(&res)
if err != nil {
return
}
err = nil
return
}
答案1
得分: 1
你可以这样做:
func (b *Mbase) GetObj(attr string, val string, result interface{}) error {
return b.coll.Find(bson.M{attr: val}).One(result)
}
不过感觉这个辅助函数并没有太多用处。Find+One本身已经是通用的了。如果只需要这个功能,我还建议你考虑使用bson.D{{attr, val}}
代替bson.M。
另外,请考虑一次只在一个论坛上提问问题。
英文:
You can do something like:
func (b *Mbase) GetObj(attr string, val string, result interface{}) error {
return b.coll.Find(bson.M{attr: val}).One(result)
}
Doesn't feel like the helper is doing much good, though. Find+One
itself is already generic. I'd also consider using bson.D{{attr, val}}
instead of bson.M if that's all you need.
Also, please consider asking questions in a single forum at a time.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论