首页 文章

Go:接口作为返回值

提问于
浏览
1

我有几个结构,我填充MongoDB的数据 .

type Dog struct {
    Id string
    Age int
}

type Invoice struct {
    Id int
    Amount float
}

我试图创建这样的函数:

func LookUp(collection string, ids []string) []interface{} {
         // Is in cache?
         // if not get them from database
    }

这样我可以做类似的事情:

func GoodDogs() []string{
             // Give the ids of good dogs
        }

 dogsIds := GoodDogs()
 dogs := LookUp("Dogs", namesToRetrieve)

我知道我可以为每个结构反复编写相同的函数,设置正确的返回类型和id类型(注意一些是int,一些字符串)但是......似乎太反DRY了 .

对于输入,接口似乎以另一种方式工作 . 有办法做我正在尝试的事情吗?或者这只是一个错误的设计模式?

2 回答

  • 0

    将指针传递给sice作为参数:

    func LookUp(collection string, ids []string, result interface{}) error {
         // Is in cache?
         // if not get them from database
         return db.C(collection).Find(bson.M{"_id": bson.M{"$in": ids}}).All(result)
    }
    

    像这样称呼它:

    var dogs []*Doc
    err := Lookup("dog", dogIds, &dogs)
    if err != nil 
       // handle error
    }
    
  • 0

    通常,使用MongoDB,您可以use bson struct快速添加或检索对象( embedded documents ) .

    你可以看到this example

    // Find the actors in the movie
    var m Movie
    db.C("movies").Find(bson.M{"name": "Fantastic Mr. Fox"}).One(&m)
    

    这意味着每个结构确实有一个Lookup函数 .

相关问题