Junior — Middle
In which cases is it safe to read data from a Map that has not yet been explicitly initialized?
sobes.tech AI
Answer from AI
In Go, reading from a map that has not been explicitly initialized (i.e., is nil) is safe but with limitations.
If the map is nil, then:
- Reading a value by key returns the zero value of the element type and
falsewhen checking for the key's existence. - Writing (assigning) to such a
mapwill cause a panic.
Example:
var m map[string]int // m == nil
value, ok := m["key"] // safe, value == 0, ok == false
// m["key"] = 10 // panic: assignment to entry in nil map
Thus, it is safe to read from a map if it is not initialized, but you cannot write to it. To write, you need to initialize the map beforehand using make.