Junior — Middle
Is it possible to add elements to a Map that has not been created or initialized?
sobes.tech AI
Answer from AI
In Go, you cannot add elements to a map if it has not been initialized. When declaring a variable of type map without initialization, it has a value of nil, and attempting to write to such a map will cause a runtime panic.
To add elements, you must first create a map using the make function or initialize it with a literal:
var m map[string]int // m == nil
m["key"] = 1 // panic: assignment to entry in nil map
m = make(map[string]int) // now m is initialized
m["key"] = 1 // works
// or initialize directly
m2 := map[string]int{"initial": 10}
m2["key"] = 1 // works
Thus, before adding elements, the map must be created and not equal to nil.