Sobes.tech
Junior — Middle

Kas on võimalik väärtust välja võtta kaardilt, mis pole veel initsialiseeritud?

sobes.tech AI

Vastus AI-lt

In Go, if a map (karte) has not been initialized (i.e., it is equal to 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 does not exist.

Example:

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

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

However, if you try to write 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 must be initialized, for example, using make:

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