Sobes.tech
Junior — Middle

Каким образом обрабатывать ситуации, когда Map еще не была инициализирована?

sobes.tech AI

Vastus AI-lt

In Go, before using a map, it must be initialized, otherwise an attempt to write to it will cause a panic (runtime panic). To handle the situation when the map is not yet initialized (i.e., is nil), you can:

  • Check if the map is initialized before use:
var m map[string]int
if m == nil {
    m = make(map[string]int)
}
 m["key"] = 42
  • Or initialize the map immediately at declaration:
m := make(map[string]int)
 m["key"] = 42

Always ensure that the map is not nil before writing to it.