将动态数组结构传递给函数Golang

时间:2018-03-16 09:39:12

标签: mongodb go mgo

我想创建接受动态数组结构的函数。并用它来映射数据库中的数据* mgodb

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)
   }
}

并得到一个错误"模型不是类型",为什么? 任何答案都将受到高度赞赏!

2 个答案:

答案 0 :(得分:1)

将准备好的切片传递给mapStructResult function

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)
    }
}

答案 1 :(得分:1)

首先,没有一个名为动态结构的术语。结构字段在使用之前声明,不能更改。我们可以使用bson类型来处理数据。 Bson类型与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) } } 类似,用于动态保存数据。

array.some

有关bson类型的更多信息。看看BSON

的这个godoc
相关问题