Go:作为返回值的接口

Go:作为返回值的接口,go,types,interface,Go,Types,Interface,我用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 fr

我用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
    }
var dogs []*Doc
err := Lookup("dog", dogIds, &dogs)
if err != nil 
   // handle error
}
这样我可以做一些事情,比如:

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

 dogsIds := GoodDogs()
 dogs := LookUp("Dogs", namesToRetrieve)
我知道我可以为每个结构反复编写相同的函数,设置正确的返回类型和id类型(注意有些是int,有些是字符串),但是。。。看起来太干了

对于输入,接口似乎以另一种方式工作。
有没有办法做到我想做的事?或者这只是一种错误的设计模式?

通常,使用MongoDB,您需要快速添加或检索对象(即

你可以看到


这意味着每个结构实际上只有一个查找函数。

通常,使用MongoDB,您需要快速添加或检索对象(即

你可以看到


这意味着每个结构实际上有一个查找函数。

将指向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)
}
可以这样称呼:

func LookUp(collection string, ids []string) []interface{} {
         // Is in cache?
         // if not get them from database
    }
var dogs []*Doc
err := Lookup("dog", dogIds, &dogs)
if err != nil 
   // handle error
}

将指向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)
}
可以这样称呼:

func LookUp(collection string, ids []string) []interface{} {
         // Is in cache?
         // if not get them from database
    }
var dogs []*Doc
err := Lookup("dog", dogIds, &dogs)
if err != nil 
   // handle error
}

我尝试了这个方法,但得到的结果是:“结果参数必须是片地址”。因此,我更改了参数
interface{}
=>
[]interface{}
。但是后来我得到了
无法使用&dog(type*[]dog]作为参数中的type[]interface{}来查找
@Marcos我怀疑是输入错误。对all的调用是
all(result)
,而不是
all(&result)
。我尝试了这个方法,但得到的结果是:“result参数必须是一个片地址”。所以我更改了参数
interface{code>
=>[]interface{}。但是我得到
不能使用&dog(type*[]dog]作为类型[]接口{}在查找
@Marcos的参数中,我怀疑有输入错误。对all的调用是
all(result)
,而不是
all(&result)
。调用all()方法时,我遇到了类型和指针问题。很好的例子!调用all()时,我遇到了类型和指针问题方法。很好的例子!