duanhuayong6687 2014-04-09 12:31
浏览 647
已采纳

如何创建对象数组-Go?

I am working in Go and MongoDB and having the following MongoDB schema

[   
  {
    "name":"sample",
    "time": "2014-04-05",
    "Qty":3
  },
  {
   "name":"sample",
   "time": "2014-04-05",
   "Qty":3
  }
]

I had tried using the following code to create the above document

elements := make([3]map[string]string)
elements["name"] = "karthick"
elements["date"] = "2014-04-05"
elements["qty"] = 3

fmt.Println(elements)

But it is not working.

Error : cannot make type [3]map[string]string

Any suggestion will be grateful

  • 写回答

2条回答 默认 最新

  • dongqian5384 2014-04-09 12:49
    关注

    There's a difference between arrays and slices. Arrays are compile time objects while slices are runtime objects. Arrays therefore have more information to offer to the compiler than slices (e.g. length).

    In your code, you attempt to create an array of map[string]string with 3 elements. You can do this like this:

    maps := [3]map[string]string{
        make(map[string]string),
        make(map[string]string),
        make(map[string]string),
    }
    

    You must call make for each map, otherwise the maps would be uninitialized (nil).

    You can also create a slice with 3 (uninitialized) elements with make:

    maps := make([]map[string]string, 3)
    

    In this case you'd have to iterate over maps and initialize each element with make.

    The simplest solution, in case you're using mgo would be to create a struct for your data:

    type Item struct {
        Name string `bson:name`
        Date string `bson:date`
        Qty int `bson:qty`
    }
    

    and use it in your array:

    var items [3]*Item
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况