Reputation: 731
I need to create a map as shown below:
package main
import "fmt"
func main() {
var data = map[string]interface{}{}
data["name"] = "User"
data["info"] = map[string]string{}
data["info"]["email"] = "[email protected]"
fmt.Println(data)
}
I am trying to create nested maps, but I am getting an error as shown below:
# command-line-arguments./interface.go:9: invalid operation: data["info"]["email"] (type interface {} does not support indexing)
Please provide solution to fix this error. Thanks in advance.
Upvotes: 2
Views: 4607
Reputation: 12675
According to Golang Laws of Reflection
A variable of interface type stores a pair: the concrete value assigned to the variable, and that value's type descriptor. To be more precise, the value is the underlying concrete data item that implements the interface and the type describes the full type of that item
That's why we needs to type assert map[string]string
to get the underlying value of map[string]interface{}
You also might wants to look at this post
For an example you can loop on maps they have indexes. But interface act like a wrapper around type T storing the value and its type. They don't have indexes as the error said.
Upvotes: 0
Reputation: 434665
Your data
:
var data = map[string]interface{}{}
is a map from string
to interface{}
so data["info"]
is just an interface{}
until you assert its type as map[string]string
:
data["info"].(map[string]string) // Now you have a map[string]string
Once you have a map[string]string
, you can index it as desired:
data["info"].(map[string]string)["email"] = "[email protected]"
https://play.golang.org/p/yuyAN9FRCxc
Upvotes: 4