Junior — Middle
How is access to values in a dictionary that has not been pre-created performed?
sobes.tech AI
Answer from AI
In Go, if a map has not been created yet (i.e., it is nil), attempting to access elements by key will not cause a panic; it will simply return the zero value for the element type.
For example:
var m map[string]int // m == nil
fmt.Println(m["key"]) // Will print 0, no error
However, attempting to assign a value to a nil map will cause a panic:
m["key"] = 10 // panic: assignment to entry in nil map
Therefore, before writing to a map, ensure it is initialized, for example:
m = make(map[string]int)
m["key"] = 10
Thus, reading from a nil map is safe, but writing requires initialization.