Junior — Middle
What behavior is expected when addressing an element in a map?
sobes.tech AI
Answer from AI
In Go, when accessing an element of a map by key, if the key exists, the corresponding value is returned. If the key does not exist, the default value for the value type is returned (for example, 0 for numbers, "" for strings, nil for pointers).
To distinguish whether a key exists in the map, the second return value — a boolean indicating the presence of the key — is usually used:
value, ok := myMap[key]
if ok {
// key exists, can use value
} else {
// key does not exist
}
Thus, when accessing a map with a non-existent key, the program does not crash but returns the "zero" value of the type and a flag indicating the absence of the key.