Sobes.tech
Senior

Can we add an element to a nil map the same way as to a nil slice?

sobes.tech AI

Answer from AI

In Go, you cannot add an element to a nil map — this will cause a runtime panic.

A map must be initialized before use, for example with make:

var m map[string]int // m == nil
m["key"] = 1 // panic: assignment to entry in nil map

m = make(map[string]int)
m["key"] = 1 // works correctly

Unlike slices, to which you can apply append even if they are nil (in which case a new slice is created), maps require explicit initialization.

Therefore, before adding elements to a map, always ensure that it is not nil and has been initialized.

Can we add an element to a nil map the same way as to… - sobes.tech