How to Check If a Map Key Exists in Go

In Go, a map is a powerful data structure that stores key-value pairs, providing efficient retrieval of data using keys. However, a challenge arises when accessing a map key that might not exist.

If the key is absent, Go returns the zero value for the map’s value type, which can be ambiguous if a key is present but its value is intentionally set to the zero value.

Consider the following example:

go
func main() {
	m1 := map[string]int{
		"a": 0,
		"b": 1,
		"c": 2,
	}

	// "a" key exists with a value of 0
	v1 := m1["a"]
	fmt.Println(v1) // 0

	// "f" key does not exist, also outputs 0
	v2 := m1["f"]
	fmt.Println(v2) // 0

	// How to tell them apart?
}

To address this, you can use an index expression, which returns a second boolean value indicating the presence of the key:

go
func main() {
	m1 := map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}

	if v, exists := m1["a"]; exists {
		// The "a" key exists in map
		fmt.Println(v) // 1
	} else {
		// if "a" does not exist
		fmt.Println("Key not found")
	}

	// 'v' and 'exists' are not accessible here
}

If you need to use the v and exists variables outside the if block, declare them beforehand:

go
func main() {
	m1 := map[string]int{
		"a": 1,
		"b": 2,
		"c": 3,
	}

	v, exists := m1["a"]
	if exists {
		// The "a" key exists in map
		fmt.Println(v) // 1
	} else {
		// "a" does not exist
		m1["a"] = 40
	}
	// `v` and `exists` remain accessible
}

The exists (or commonly named ok) variable will be true if the key exists:

go
v, ok := m1["a"]
if ok {
	fmt.Println(v)
}

To check for a key’s presence without needing its value, use the blank identifier _:

go
_, ok := m1["a"]
if ok {
	// Key exists
}

Thanks for reading, and happy coding!