Mongodb 将动态数组结构传递给函数Golang
我想创建一个接受“dynamic array struct”的函数,并使用它从数据库*mgodb映射数据Mongodb 将动态数组结构传递给函数Golang,mongodb,go,mgo,Mongodb,Go,Mgo,我想创建一个接受“dynamic array struct”的函数,并使用它从数据库*mgodb映射数据 type Cats struct { Meow string } func getCatsPagination() { mapStructResult("Animality","Cat_Col", Cats) } type Dogs struct { Bark string } func getDogsPagination() { mapStructResult("
type Cats struct {
Meow string
}
func getCatsPagination() {
mapStructResult("Animality","Cat_Col", Cats)
}
type Dogs struct {
Bark string
}
func getDogsPagination() {
mapStructResult("Animality","Dog_Col", Dogs)
}
func mapStructResult(db string, collection string, model interface{}) {
result := []model{} //gets an error here
err := con.Find(param).Limit(int(limit)).Skip(int(offset)).All(&result) // map any database result to 'any' struct provided
if err != nil {
log.Fatal(err)
}
}
并得到一个错误,因为“模型不是类型”,为什么?
任何回答都将不胜感激 将就绪切片传递给
mapStructResult函数
type Cats struct {
Meow string
}
func getCatsPagination() {
cats := []Cats{}
mapStructResult("Animality", "Cat_Col", &cats)
}
type Dogs struct {
Bark string
}
func getDogsPagination() {
dogs := []Dogs{}
mapStructResult("Animality", "Dog_Col", &dogs)
}
func mapStructResult(db string, collection string, model interface{}) {
err := con.Find(param).Limit(int(limit)).Skip(int(offset)).All(result) // map any database result to 'any' struct provided
if err != nil {
log.Fatal(err)
}
}
首先,go中没有称为动态结构的术语。结构字段在使用前声明,不能更改。我们可以使用bson类型来处理数据。Bson类型类似于用来动态保存数据的
map[string]接口{}
func mapStructResult(db string, collection string, model interface{}) {
var result []bson.M // bson.M works like map[string]interface{}
err := con.Find(param).Limit(int(limit)).Skip(int(offset)).All(&result) // map any database result to 'any' struct provided
if err != nil {
log.Fatal(err)
}
}
有关bson类型的详细信息。查看此godoc以查找错误是因为
模型
是函数的参数mapStructResult
不是类型。不能将类型传递给函数,必须传递值。只有一对内置函数,例如new
,或make
,可以接受类型作为参数。也就是说,model interface{}
可以是任何类型的值,Dogs
是类型名称,而不是值。