Junior
How is key-based value lookup performed in the map data structure in Go?
sobes.tech AI
Answer from AI
Searching for a value by key is done using the index access syntax: value, ok := mapName[key]. This syntax returns two values: the value associated with the key (value), and a boolean (ok) indicating whether the key was found in the map. If the key is absent, value will be the zero value of the map's element type, and ok will be false.
func findInMap(m map[string]int, key string) (int, bool) {
// Search for a value by key
value, ok := m[key]
// ok will be true if the key is found, false otherwise
// value will contain the value if the key is found, or the zero value of int (0) otherwise
return value, ok
}