我有几个结构,我填充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 回答
将指针传递给sice作为参数:
像这样称呼它:
通常,使用MongoDB,您可以use bson struct快速添加或检索对象( embedded documents ) .
你可以看到this example
这意味着每个结构确实有一个Lookup函数 .