Junior — Middle
What happens when working with a Map object if it is not initialized with make or assigned a value at declaration?
sobes.tech AI
Answer from AI
In Go, an object of type map when declared without initialization (via make or assigning a value) has the value nil. Attempting to write an element to such a nil-map will cause a runtime panic. However, reading from a nil-map is safe and will simply return the zero value for the value type.
Example:
var m map[string]int // m == nil
// Safe to read:
fmt.Println(m["key"]) // Will print 0
// Writing will cause a panic:
m["key"] = 10 // panic: assignment to entry in nil map
Therefore, before using a map for writing, it must be initialized, for example:
m = make(map[string]int)