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

如何创建对象数组-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

图片转代码服务由CSDN问答提供 功能建议

我在 Go MongoDB 中工作, 以下MongoDB模式

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

我尝试使用以下代码创建上述文档

  elements:= make([3] map [string  ] string)
elements [“ name”] =“ karthick” 
elements [“ date”] =“ 2014-04-05” 
elements [“ qty”] = 3 
 
fmt.Println(elements)
 <  / code>  
 
 

,但无法正常工作。

 错误:无法使类型[3] map [string] string 
 <  / code>  
 
 

任何建议将不胜感激

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dplsnw7329 2014-04-09 12:36

    What do you want to achieve? You mixed syntax for creating array and map.

    Here is working example.

    package main
    
    import "fmt"
    
    func main() {
        elements := make(map[string]interface{})
        elements["name"] = "karthick"
        elements["date"] = "2014-04-05"
        elements["qty"] = 3
    
        fmt.Println(elements)
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题