Sobes.tech
Junior — Middle

Is it possible to extract a value from a map that has not been initialized yet?

sobes.tech AI

Answer from AI

In Go, if a map has not been initialized (i.e., it is nil), attempting to retrieve a value by key will not cause a panic, but will simply return the zero value for the value type and a boolean flag false indicating that the key is absent.

Example:

var m map[string]int // m == nil

value, ok := m["key"]
fmt.Println(value, ok) // Outputs: 0 false

However, if you try to assign a value to an uninitialized map, a panic will occur:

m["key"] = 10 // panic: assignment to entry in nil map

Therefore, to use a map safely, it needs to be initialized, for example, using make:

m = make(map[string]int)
m["key"] = 10 // now it works correctly