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

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)