英文:
How to create array of objects - Go?
问题
我正在使用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)
但是它不起作用。
错误:无法创建类型[3]map[string]string。
任何建议将不胜感激。
英文:
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
答案1
得分: 10
数组和切片之间有一些区别。数组是编译时对象,而切片是运行时对象。因此,与切片相比,数组可以向编译器提供更多的信息(例如长度)。
在你的代码中,你尝试创建一个包含3个map[string]string
元素的数组。你可以这样做:
maps := [3]map[string]string{
make(map[string]string),
make(map[string]string),
make(map[string]string),
}
你必须为每个map调用make
,否则这些map将未初始化(nil)。
你也可以使用make
创建一个包含3个(未初始化)元素的切片:
maps := make([]map[string]string, 3)
在这种情况下,你需要遍历maps
并使用make
初始化每个元素。
如果你使用mgo,最简单的解决方案是为你的数据创建一个结构体:
type Item struct {
Name string `bson:name`
Date string `bson:date`
Qty int `bson:qty`
}
然后在数组中使用它:
var items [3]*Item
英文:
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
答案2
得分: 1
你想要实现什么?你混合了创建数组和映射的语法。
这里是一个可工作的示例。
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)
}
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论