A map maps keys to values. The zero value of a map is nil . A nil map has no keys, nor can keys be added. The make function returns a map of the given type, initialized and ready for use.
Go by Example: Maps To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.
Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.
Create Empty Map in Golang To create an empty Map in Go language, we can either use make() function with map type specified or use map initializer with no key:value pairs given. Create an empty Map: string->string using make() function with the following syntax.
You have not initialized your inner map. Before your for loop you can add m["uid"] = make(map[string]T)
and then assign the name.
You should check if the map is nil and initialize one if it's nil inside the for loop:
if m["uid"] == nil {
m["uid"] = map[string]T{}
}
There is thing as per the error
assignment to entry in nil map
For nested maps when assign to the deep level key we needs to be certain that its outer key has value. Else it will say that the map is nil. For eg in your case
m := make(map[string]map[string]T, len(names))
m is a nested map which contains string
key with map[string]T
as value. And you are assign the value
m["uid"][name] = T{cn: "Chaithra", street: "fkmp"}
here you can see the m["uid"]
is nil
and we are stating it contains a value [name]
which is a key to nested value of type T
. So first you need to assign value to "uid" or initialise it as
m["uid"] = make(map[string]T)
Probably the map you have define is by using variable
var m map[string]interface{}
Instead use
m := make(map[string]interface{})
to avoid respective error
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With