3

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
  • 2
    It's probably worth reading up on slices and deciding first if you really want to use an array or should actually be using a slice: blog.golang.org/slices Commented Apr 9, 2014 at 12:48

2 Answers 2

10

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

Thanks. Above code will create only object. My doubt is how to create array of object as mentioned in the question.
so @nemo answer is better or you can keep array of maps but I have no idea how it will work with mongo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.