将方法转换为通用方式,使用mgo查找

huangapple go评论87阅读模式
英文:

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:&quot;first_name&quot;`
	LastName   string        `bson:&quot;last_name&quot;`
}

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(&amp;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.

huangapple
  • 本文由 发表于 2014年8月21日 23:44:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/25430541.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定