2

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.

1
  • @mu is too short answer is current. But why do you need it in the first place? map is a data structure suitable for search. It may be the right thing to do in your case but It looks a bit odd. Commented Mar 13, 2018 at 9:22

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.