douhu8851 2018-03-16 09:39
浏览 46
已采纳

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

I want to create function that accept 'dynamic array struct' and use it to map a data from database *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)
   }
}

and gets an error as "model is not a type", why is it? any answer will be highly appreciated !

  • 写回答

2条回答 默认 最新

  • dsv73806 2018-03-16 09:52
    关注

    Pass the ready slice to the 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条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程